ToArray::toArray()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 4
nop 0
dl 0
loc 23
ccs 13
cts 13
cp 1
crap 5
rs 9.5222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VasilDakov\Speedy\Traits;
6
7
use ReflectionClass;
8
use RuntimeException;
9
use VasilDakov\Speedy\Property;
10
11
trait ToArray
12
{
13
    /**
14
     * @param string $name
15
     * @return Property|null
16
     * @throws RuntimeException
17
     */
18 23
    private function getProperty(string $name): ?Property
19
    {
20 23
        $cases = Property::cases();
21 23
        $key   = \array_search($name, \array_column($cases, 'value'));
22
23 23
        $property = Property::tryFrom($cases[$key]->value);
24
25 23
        if (! $property instanceof Property) {
26
            throw new RuntimeException(
27
                \sprintf('Property % can not be found', $name)
28
            );
29
        }
30
31 23
        return $property;
32
    }
33
34 26
    public function toArray(): array
35
    {
36 26
        $array = [];
37
38 26
        $reflection = new ReflectionClass($this);
39 26
        $classProperties = $reflection->getProperties();
40
41 26
        foreach ($classProperties as $classProperty) {
42 25
            if ($classProperty->getValue($this)) {
43 23
                $value = $classProperty->getValue($this);
44 23
                $name  = $classProperty->getName();
45
46 23
                $property = $this->getProperty($name);
47
48 23
                if (\is_object($value) && \method_exists($value, 'toArray')) {
49 9
                    $array[$property->value] = $value->toArray();
50
                } else {
51 23
                    $array[$property->value] = $classProperty->getValue($this);
52
                }
53
            }
54
        }
55
56 26
        return $array;
57
    }
58
}
59