Passed
Push — master ( 377229...76c4a0 )
by Midori
13:42
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 lcfirst;
12
use function preg_match;
13
use function preg_replace;
14
use function str_replace;
15
use function strtolower;
16
use function ucwords;
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
                $toReturn[self::makeKebab($varName)] = $this->$methodName();
37
            }
38
        }
39
        return $toReturn;
40
    }
41
42
    /**
43
     * Expects the implemented class has proper constructor parameters matching array keys.
44
     *
45
     * @return mixed
46
     * @throws ReflectionException
47
     */
48
    public static function fromArray(array $data)
49
    {
50
        $constructorArray = [];
51
        $reflection = new ReflectionClass(static::class);
52
        $constructor = $reflection->getConstructor();
53
        $params = $constructor->getParameters();
54
55
        foreach ($params as $param) {
56
            $paramName = $param->getName();
57
            $constructorArray[] = $data[self::makeCamel($paramName)] ?? null;
58
        }
59
60
        return $reflection->newInstanceArgs($constructorArray);
61
    }
62
63
    private static function makeKebab($camel): string
64
    {
65
        return strtolower(preg_replace('%([A-Z])([a-z])%', '_\1\2', $camel));
66
    }
67
68
    private static function makeCamel($kebab, $capitalizeFirstCharacter = false)
69
    {
70
        $str = str_replace('-', '', ucwords($kebab, '-'));
71
72
        if (!$capitalizeFirstCharacter) {
73
            $str = lcfirst($str);
74
        }
75
76
        return $str;
77
    }
78
}
79