Passed
Push — master ( 443842...86f0b2 )
by Joshua
05:55 queued 01:59
created

HydratorTrait::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SeamsCMS\Delivery\Model;
4
5
use GeneratedHydrator\Configuration;
6
7
trait HydratorTrait
8
{
9
    private static $hydrators = array();
10
11 2
    public static function fromArray(array $data)
12
    {
13 2
        $data = self::convertNames($data);
14
15 2
        $hydrator = self::getHydrator();
16 2
        $object = new static();
17
18 2
        $hydrator->hydrate($data, $object);
19
20 2
        return $object;
21
    }
22
23
    /**
24
     * Returns an array where all keys have been converted from snake_case to camelCase
25
     *
26
     * @param array $data
27
     *
28
     * @return array
29
     */
30 2
    private static function convertNames(array $data): array
31
    {
32 2
        $result = [];
33
34 2
        foreach ($data as $key => $value) {
35 2
            $parts = explode('_', $key);
36 2
            foreach ($parts as &$part) {
37 2
                $part = ucfirst($part);
38
            }
39 2
            $key = implode("", $parts);
40 2
            $key = lcfirst($key);
41 2
            $result[$key] = $value;
42
        }
43
44 2
        return $result;
45
    }
46
47 2
    private static function getHydrator()
48
    {
49 2
        $className = static::class;
50
51 2
        if (!isset(self::$hydrators[$className])) {
52 1
            $configuration = new Configuration($className);
53 1
            $hydratorClass = $configuration->createFactory()->getHydratorClass();
54 1
            self::$hydrators[$className] = new $hydratorClass();
55
        }
56
57 2
        return self::$hydrators[$className];
58
    }
59
}
60