Passed
Push — master ( c2f5d4...3262e6 )
by Jesse
02:44
created

ReflectiveHydrator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 1
eloc 0
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use ReflectionClass;
7
use ReflectionObject;
8
9
/**
10
 * Hydrates an inheriting object from array input.
11
 *
12
 * Slower than the default object hydrator, but useful in the context of
13
 * inheritance, when some of the properties are private to the parent class and
14
 * therefore inaccessible through simple closure binding.
15
 *
16
 * @package Stratadox\Hydrate
17
 * @author  Stratadox
18
 */
19
final class ReflectiveHydrator implements Hydrates
20
{
21
    private function __construct()
22
    {
23
    }
24
25
    /**
26
     * Produce a reflective hydrator.
27
     *
28
     * @return Hydrates A hydrator that uses reflection to write properties.
29
     */
30
    public static function default(): Hydrates
31
    {
32
        return new ReflectiveHydrator;
33
    }
34
35
    /** @inheritdoc */
36
    public function writeTo(object $target, array $data): void
37
    {
38
        $object = new ReflectionObject($target);
39
        foreach ($data as $name => $value) {
40
            $this->write($object, $target, $name, $value);
41
        }
42
    }
43
44
    private function write(
45
        ReflectionClass $object,
46
        object $target,
47
        string $name,
48
        $value
49
    ): void {
50
        while ($object && !$object->hasProperty($name)) {
51
            $object = $object->getParentClass();
52
        }
53
        // @todo if !object, write as public?
54
        $property = $object->getProperty($name);
55
        $property->setAccessible(true);
56
        $property->setValue($target, $value);
57
    }
58
}
59