Passed
Push — main ( 985f30...2b2caa )
by Vasil
03:30
created

ToArray   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 86.36%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 46
ccs 19
cts 22
cp 0.8636
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A toArray() 0 23 5
A getProperty() 0 14 2
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