Arrayizes::toArray()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
/*
4
 * This file is part of the PHP-UNDERSCORE package.
5
 *
6
 * (c) Jitendra Adhikari <[email protected]>
7
 *     <https://github.com/adhocore>
8
 *
9
 * Licensed under MIT license.
10
 */
11
12
namespace Ahc\Underscore;
13
14
trait Arrayizes
15
{
16
    /**
17
     * Get data as array.
18
     *
19
     * @param mixed $data Arbitrary data.
20
     * @param bool  $cast Force casting to array!
21
     *
22
     * @return array
23
     */
24
    public function asArray($data, $cast = true)
25
    {
26
        if (\is_array($data)) {
27
            return $data;
28
        }
29
30
        if ($data instanceof static) {
31
            return $data->get();
0 ignored issues
show
Bug introduced by
It seems like get() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

31
            return $data->/** @scrutinizer ignore-call */ get();
Loading history...
32
        }
33
34
        // @codeCoverageIgnoreStart
35
        if ($data instanceof \Traversable) {
36
            return \iterator_to_array($data);
37
        }
38
        // @codeCoverageIgnoreEnd
39
40
        if ($data instanceof \JsonSerializable) {
41
            return $data->jsonSerialize();
42
        }
43
44
        if (\method_exists($data, 'toArray')) {
45
            return $data->toArray();
46
        }
47
48
        return  $cast ? (array) $data : $data;
49
    }
50
51
    /**
52
     * Convert the data items to array.
53
     *
54
     * @return array
55
     */
56
    public function toArray()
57
    {
58
        return \array_map(function ($value) {
59
            if (\is_scalar($value)) {
60
                return $value;
61
            }
62
63
            return $this->asArray($value, false);
64
        }, $this->getData());
0 ignored issues
show
Bug introduced by
It seems like getData() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
        }, $this->/** @scrutinizer ignore-call */ getData());
Loading history...
65
    }
66
}
67