Completed
Pull Request — master (#5)
by Fiser
06:42
created

Hydrator::setValuesToObject()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 6
nop 3
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace LIN3S\SharedKernel\Infrastructure\Persistence\Sql;
15
16
use LIN3S\SharedKernel\Exception\Exception;
17
18
/**
19
 * @author Rubén García <[email protected]>
20
 */
21
final class Hydrator
22
{
23
    public function constructObjectWith(string $class, array $values)
24
    {
25
        $reflectionClass = new \ReflectionClass($class);
26
        $object = $reflectionClass->newInstanceWithoutConstructor();
27
        $this->setValuesToObject($reflectionClass, $object, $values);
28
29
        Return $object;
30
    }
31
32
    private function setValuesToObject(\ReflectionClass $reflectionClass, $object, array $values)
33
    {
34
        foreach ($values as $key => $value) {
35
            if (!$reflectionClass->hasProperty($key)) {
36
                throw new Exception(
37
                    'Property ' . $key . ' doesn\'t exist in construction of object ' . $reflectionClass->getName()
38
                );
39
            }
40
            $refProperty = $reflectionClass->getProperty($key);
41
            if (!$refProperty->getDeclaringClass()->getName() === $reflectionClass->getName()) {
42
                throw new Exception(
43
                    'Property has declaring class '
44
                    . $refProperty->getDeclaringClass()->getName()
45
                    . ' but insert '
46
                    . $reflectionClass->getName()
47
                );
48
            }
49
            $refProperty->setAccessible(true);
50
            $refProperty->setValue($object, $value);
51
            unset($values[$key]);
52
        }
53
        if ($reflectionClass->getParentClass()) {
54
            $object = $this->setValuesToObject($reflectionClass->getParentClass(), $object, $values);
55
        }
56
        return $object;
57
    }
58
}
59