Completed
Push — master ( 0e7db1...c18576 )
by Tomasz
12s
created

ReflectionHydrator::computeValue()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 12
cts 12
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 4
nop 3
crap 4
1
<?php
2
namespace Thunder\Serializard\Hydrator;
3
4
use Thunder\Serializard\HydratorContainer\HydratorContainerInterface;
5
6
final class ReflectionHydrator
7
{
8
    private $class;
9
    private $objects;
10
11 2
    public function __construct($class, array $objects)
12
    {
13 2
        if(false === class_exists($class)) {
14 1
            throw new \InvalidArgumentException(sprintf('Unknown hydration class %s!', $class));
15
        }
16
17 1
        $this->class = $class;
18 1
        $this->objects = $objects;
19 1
    }
20
21 1
    public function __invoke(array $data, HydratorContainerInterface $hydrators)
22
    {
23 1
        $ref = new \ReflectionClass($this->class);
24 1
        $object = $ref->newInstanceWithoutConstructor();
0 ignored issues
show
Bug introduced by
The method newInstanceWithoutConstructor() does not exist on ReflectionClass. Did you maybe mean newInstance()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
25
26 1
        foreach($ref->getProperties() as $property) {
27 1
            $name = $property->getName();
28 1
            if(false === array_key_exists($name, $data)) {
29 1
                continue;
30
            }
31
32 1
            $property->setAccessible(true);
33 1
            $property->setValue($object, $this->computeValue($name, $data[$name], $hydrators));
34 1
        }
35
36 1
        return $object;
37
    }
38
39 1
    private function computeValue($name, $data, HydratorContainerInterface $hydrators)
40
    {
41 1
        if(false === array_key_exists($name, $this->objects)) {
42 1
            return $data;
43
        }
44
45 1
        $type = $this->objects[$name];
46 1
        if('[]' !== substr($type, -2)) {
47 1
            return call_user_func($hydrators->getHandler($this->objects[$name]), $data, $hydrators);
48
        }
49
50 1
        $type = substr($type, 0, -2);
51 1
        $items = array();
52 1
        foreach($data as $item) {
53 1
            $items[] = call_user_func($hydrators->getHandler($type), $item, $hydrators);
54 1
        }
55
56 1
        return $items;
57
    }
58
}
59