|
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
|
|
|
|
|
62
|
|
|
if($object instanceof \stdClass) { |
|
63
|
|
|
return get_object_vars($object); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$data = []; |
|
67
|
|
|
try { |
|
68
|
|
|
$reflection = new \ReflectionClass($object); |
|
69
|
|
|
} catch (\ReflectionException $e) { |
|
70
|
|
|
return $data; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
$properties = $reflection->getProperties(); |
|
74
|
|
|
/** @var \ReflectionProperty $property */ |
|
75
|
|
|
foreach($properties as $property) { |
|
76
|
|
|
$property->setAccessible(true); |
|
77
|
|
|
$data[$property->getName()] = $property->getValue($object); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
return $data; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|