ArrayConvertableTrait::fromArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace midorikocak\arraytools;
6
7
use ReflectionClass;
8
use ReflectionException;
9
use ReflectionMethod;
10
11
use function is_array;
12
use function is_object;
13
use function lcfirst;
14
use function preg_match;
15
use function preg_replace;
16
use function strtolower;
17
18
trait ArrayConvertableTrait
19
{
20
    /**
21
     * Expects that implemented class has getters matching array keys.
22
     *
23
     * @throws ReflectionException
24
     */
25 1
    public function toArray(): array
26
    {
27 1
        $toReturn = [];
28 1
        $reflection = new ReflectionClass(static::class);
29 1
        $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
30
31 1
        foreach ($methods as $method) {
32 1
            $methodName = $method->getName();
33 1
            $isGetter = preg_match('~get([A-Z].+)~', $methodName, $matches);
34 1
            if ($isGetter) {
35 1
                $varName = lcfirst($matches[1]);
36 1
                $varValue = $this->$methodName();
37 1
                if (is_array($varValue)) {
38
                    foreach ($varValue as &$value) {
39
                        if (is_object($value)) {
40
                            $value = $value->toArray();
41
                        }
42
                    }
43
                }
44 1
                $toReturn[self::makeKebab($varName)] = $varValue;
45
            }
46
        }
47 1
        return $toReturn;
48
    }
49
50
    /**
51
     * Expects the implemented class has proper constructor parameters matching array keys.
52
     *
53
     * @return mixed
54
     * @throws ReflectionException
55
     */
56 1
    public static function fromArray(array $data)
57
    {
58 1
        $constructorArray = [];
59 1
        $reflection = new ReflectionClass(static::class);
60 1
        $constructor = $reflection->getConstructor();
61 1
        $params = $constructor->getParameters();
62
63 1
        foreach ($params as $param) {
64 1
            $paramName = $param->getName();
65 1
            $constructorArray[] = $data[self::makeKebab($paramName)] ?? null;
66
        }
67
68 1
        return $reflection->newInstanceArgs($constructorArray);
69
    }
70
71 2
    private static function makeKebab($camel): string
72
    {
73 2
        return strtolower(preg_replace('%([A-Z])([a-z])%', '_\1\2', $camel));
74
    }
75
}
76