ToArrayTrait::toArrayValueInsideToArrayTrait()   B
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 7
nop 1
dl 0
loc 18
ccs 12
cts 12
cp 1
crap 6
rs 8.8571
c 0
b 0
f 0
1
<?php
2
namespace ConstructNamedParameters\Traits;
3
4
trait ToArrayTrait
5
{
6
    /**
7
     * Export all the object properties recursivelly
8
     * For each property, if the value of the property is:
9
     * - object and has a method toArray returns the method
10
     * - object or array return an array with all properties expoerted with this same routine
11
     * - else return the property value
12
     *
13
     * @return array
14
     */
15 1
    public function toArray()
16
    {
17 1
        $values = [];
18 1
        foreach ($this as $property => $value) {
0 ignored issues
show
Bug introduced by
The expression $this of type this<ConstructNamedParam...rs\Traits\ToArrayTrait> is not traversable.
Loading history...
19 1
            $values[$property] = $this->toArrayValueInsideToArrayTrait($value);
20
        }
21 1
        return $values;
22
    }
23
24 1
    private function toArrayValueInsideToArrayTrait($value)
25
    {
26 1
        $isObject = is_object($value);
27 1
        if ($isObject) {
28 1
            $methodToArray = [$value, 'toArray'];
29 1
            if (is_callable($methodToArray)) {
30 1
                return call_user_func($methodToArray);
31
            }
32
        }
33 1
        if ($isObject || is_array($value)) {
34 1
            $children = [];
35 1
            foreach ($value as $key => $child) {
36 1
                $children[$key] = $this->toArrayValueInsideToArrayTrait($child);
37
            }
38 1
            return $children;
39
        }
40 1
        return $value;
41
    }
42
}
43