Completed
Push — master ( df8b27...5474af )
by Midori
12:27 queued 11s
created

ArrayConvertableTrait::makeCamel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
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
    public function toArray(): array
26
    {
27
        $toReturn = [];
28
        $reflection = new ReflectionClass(static::class);
29
        $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
30
31
        foreach ($methods as $method) {
32
            $methodName = $method->getName();
33
            $isGetter = preg_match('~get([A-Z].+)~', $methodName, $matches);
34
            if ($isGetter) {
35
                $varName = lcfirst($matches[1]);
36
                $varValue = $this->$methodName();
37
                if (is_array($varValue)) {
38
                    foreach ($varValue as &$value) {
39
                        if (is_object($value)) {
40
                            $value = $value->toArray();
41
                        }
42
                    }
43
                }
44
                $toReturn[self::makeKebab($varName)] = $varValue;
45
            }
46
        }
47
        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
    public static function fromArray(array $data)
57
    {
58
        $constructorArray = [];
59
        $reflection = new ReflectionClass(static::class);
60
        $constructor = $reflection->getConstructor();
61
        $params = $constructor->getParameters();
62
63
        foreach ($params as $param) {
64
            $paramName = $param->getName();
65
            $constructorArray[] = $data[self::makeKebab($paramName)] ?? null;
66
        }
67
68
        return $reflection->newInstanceArgs($constructorArray);
69
    }
70
71
    private static function makeKebab($camel): string
72
    {
73
        return strtolower(preg_replace('%([A-Z])([a-z])%', '_\1\2', $camel));
74
    }
75
}
76