1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sf4\Populator; |
4
|
|
|
|
5
|
|
|
class Populator implements PopulatorInterface |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Context Factory |
9
|
|
|
* @var HydratorContextFactoryInterface |
10
|
|
|
*/ |
11
|
|
|
protected $factory; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Hydrator |
15
|
|
|
* @var HydratorInterface |
16
|
|
|
*/ |
17
|
|
|
protected $hydrator; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Constructor |
21
|
|
|
* |
22
|
|
|
* @param HydratorInterface $hydrator An Hydrator |
23
|
|
|
* @param HydratorContextFactoryInterface $factory An Hydrator Context Factory |
24
|
|
|
*/ |
25
|
3 |
|
public function __construct(HydratorInterface $hydrator = null, HydratorContextFactoryInterface $factory = null) |
26
|
|
|
{ |
27
|
3 |
|
$this->hydrator = $hydrator ?: new Hydrator; |
28
|
3 |
|
$this->factory = $factory ?: new HydratorContextFactory(); |
29
|
3 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Populates the given data to the given object |
33
|
|
|
* |
34
|
|
|
* @param $data |
35
|
|
|
* @param mixed $object Object or class name to hydrate |
36
|
|
|
* |
37
|
|
|
* @return object Hydrated object |
38
|
|
|
* @throws \ReflectionException |
39
|
|
|
*/ |
40
|
3 |
|
public function populate($data, $object) |
41
|
|
|
{ |
42
|
3 |
|
if (!is_object($object)) { |
43
|
|
|
if (!class_exists($object)) { |
44
|
|
|
throw new \InvalidArgumentException(sprintf("Class %s does not exist", $object)); |
45
|
|
|
} |
46
|
|
|
$object = new $object; |
47
|
|
|
} |
48
|
3 |
|
$context = $this->factory->build($object); |
49
|
3 |
|
return $this->hydrator->hydrate($data, $object, $context); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param mixed $object Object |
54
|
|
|
* @return array |
55
|
|
|
*/ |
56
|
|
|
public function unpopulate($object) |
57
|
|
|
{ |
58
|
|
|
if (!is_object($object)) { |
59
|
|
|
throw new \InvalidArgumentException(sprintf("Class %s does not exist", $object)); |
60
|
|
|
} |
61
|
|
|
$data = []; |
62
|
|
|
try { |
63
|
|
|
$reflection = new \ReflectionClass($object); |
64
|
|
|
} catch (\ReflectionException $e) { |
65
|
|
|
return $data; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$properties = $reflection->getProperties(); |
69
|
|
|
/** @var \ReflectionProperty $property */ |
70
|
|
|
foreach($properties as $property) { |
71
|
|
|
$data[$property->getName()] = $property->getValue($object); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $data; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|