HydratorTrait::convertNames()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.9666
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Seams-CMS Delivery SDK package.
7
 *
8
 * (c) Seams-CMS.com
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace SeamsCMS\Delivery\Model;
15
16
use GeneratedHydrator\Configuration;
17
18
/**
19
 * Trait HydratorTrait
20
 * @package SeamsCMS\Delivery\Model
21
 */
22
trait HydratorTrait
23
{
24
    /** @var array */
25
    private static $hydrators = array();
26
27
    /**
28
     * @param array $data
29
     * @return mixed
30
     */
31 31
    public static function fromArray(array $data)
32
    {
33 31
        $data = self::convertNames($data);
34
35 31
        $hydrator = self::getHydrator();
36 31
        $object = new static();
37
38 31
        $hydrator->hydrate($data, $object);
39
40 31
        return $object;
41
    }
42
43
    /**
44
     * Returns an array where all keys have been converted from snake_case to camelCase
45
     *
46
     * @param array $data
47
     *
48
     * @return array
49
     */
50 31
    private static function convertNames(array $data): array
51
    {
52 31
        $result = [];
53
54 31
        foreach ($data as $key => $value) {
55 27
            $parts = explode('_', $key);
56 27
            foreach ($parts as &$part) {
57 27
                $part = ucfirst($part);
58
            }
59 27
            $key = implode("", $parts);
60 27
            $key = lcfirst($key);
61 27
            $result[$key] = $value;
62
        }
63
64 31
        return $result;
65
    }
66
67
    /**
68
     * @return mixed
69
     */
70 31
    private static function getHydrator()
71
    {
72 31
        $className = static::class;
73
74 31
        if (!isset(self::$hydrators[$className])) {
75 17
            $configuration = new Configuration($className);
76 17
            $hydratorClass = $configuration->createFactory()->getHydratorClass();
77 17
            self::$hydrators[$className] = new $hydratorClass();
78
        }
79
80 31
        return self::$hydrators[$className];
81
    }
82
}
83