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
|
|
|
public function __construct($class, array $objects) |
12
|
|
|
{ |
13
|
|
|
if(false === class_exists($class)) { |
14
|
|
|
throw new \InvalidArgumentException(sprintf('Unknown hydration class %s!', $class)); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
$this->class = $class; |
18
|
|
|
$this->objects = $objects; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function __invoke(array $data, HydratorContainerInterface $hydrators) |
22
|
|
|
{ |
23
|
|
|
$ref = new \ReflectionClass($this->class); |
24
|
|
|
$object = $ref->newInstanceWithoutConstructor(); |
25
|
|
|
|
26
|
|
|
foreach($ref->getProperties() as $property) { |
27
|
|
|
$name = $property->getName(); |
28
|
|
|
if(false === array_key_exists($name, $data)) { |
29
|
|
|
continue; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$property->setAccessible(true); |
33
|
|
|
$property->setValue($object, $this->computeValue($name, $data[$name], $hydrators)); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $object; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
private function computeValue($name, $data, HydratorContainerInterface $hydrators) |
40
|
|
|
{ |
41
|
|
|
if(false === array_key_exists($name, $this->objects)) { |
42
|
|
|
return $data; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$type = $this->objects[$name]; |
46
|
|
|
if('[]' !== substr($type, -2)) { |
47
|
|
|
return call_user_func($hydrators->getHandler($this->objects[$name]), $data, $hydrators); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$type = substr($type, 0, -2); |
51
|
|
|
$items = array(); |
52
|
|
|
foreach($data as $item) { |
53
|
|
|
$items[] = call_user_func($hydrators->getHandler($type), $item, $hydrators); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $items; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|