ReflectionHydrator::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 12
cts 12
cp 1
rs 9.584
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
namespace Thunder\Serializard\Hydrator;
3
4
use Thunder\Serializard\Exception\ClassNotFoundException;
5
use Thunder\Serializard\Exception\UnserializationFailureException;
6
use Thunder\Serializard\HydratorContainer\HydratorContainerInterface;
7
8
final class ReflectionHydrator
9
{
10
    private $class;
11
    private $objects;
12
13 2
    public function __construct($class, array $objects)
14
    {
15 2
        $this->class = $class;
16 2
        $this->objects = $objects;
17 2
    }
18
19 2
    public function __invoke(array $data, HydratorContainerInterface $hydrators)
20
    {
21
        try {
22 2
            $ref = new \ReflectionClass($this->class);
23 1
        } catch(\ReflectionException $e) {
24 1
            throw UnserializationFailureException::fromClass($this->class);
25
        }
26 1
        $object = $ref->newInstanceWithoutConstructor();
27
28 1
        foreach($ref->getProperties() as $property) {
29 1
            $name = $property->getName();
30 1
            if(false === array_key_exists($name, $data)) {
31 1
                continue;
32
            }
33
34 1
            $property->setAccessible(true);
35 1
            $property->setValue($object, $this->computeValue($name, $data[$name], $hydrators));
36
        }
37
38 1
        return $object;
39
    }
40
41 1
    private function computeValue($name, $data, HydratorContainerInterface $hydrators)
42
    {
43 1
        if(false === array_key_exists($name, $this->objects)) {
44 1
            return $data;
45
        }
46
47 1
        $type = $this->objects[$name];
48 1
        if('[]' !== substr($type, -2)) {
49 1
            return \call_user_func($hydrators->getHandler($this->objects[$name]), $data, $hydrators);
50
        }
51
52 1
        $type = substr($type, 0, -2);
53 1
        $items = [];
54 1
        foreach($data as $item) {
55 1
            $items[] = \call_user_func($hydrators->getHandler($type), $item, $hydrators);
56
        }
57
58 1
        return $items;
59
    }
60
}
61