1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of slick/di package |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Slick\Di; |
11
|
|
|
|
12
|
|
|
use Interop\Container\ContainerInterface as InteropContainer; |
13
|
|
|
|
14
|
|
|
use Slick\Common\Inspector; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* ObjectHydrator |
18
|
|
|
* |
19
|
|
|
* @package Slick\Di |
20
|
|
|
* @author Filipe Silva <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
class ObjectHydrator implements ObjectHydratorInterface |
23
|
|
|
{ |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var Inspector |
27
|
|
|
*/ |
28
|
|
|
private $inspector; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var mixed |
32
|
|
|
*/ |
33
|
|
|
private $object; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Methods to implement the ContainerAwareInterface |
37
|
|
|
*/ |
38
|
|
|
use ContainerAwareMethods; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Creates an Object Hydrator |
42
|
|
|
* |
43
|
|
|
* @param InteropContainer $container |
44
|
|
|
*/ |
45
|
|
|
public function __construct(InteropContainer $container) |
46
|
|
|
{ |
47
|
|
|
$this->setContainer($container); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Used internal container to inject dependencies on provided object |
52
|
|
|
* |
53
|
|
|
* @param mixed $object |
54
|
|
|
* |
55
|
|
|
* @return ObjectHydrator|ObjectHydratorInterface |
56
|
|
|
*/ |
57
|
|
|
public function hydrate($object) |
58
|
|
|
{ |
59
|
|
|
$this->inspector = Inspector::forClass($object); |
60
|
|
|
$this->object = $object; |
61
|
|
|
foreach ($this->inspector->getClassMethods() as $method) { |
62
|
|
|
$this->evaluate($method); |
63
|
|
|
} |
64
|
|
|
return $this; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Evaluates method annotations and injects the dependency if needed |
69
|
|
|
* |
70
|
|
|
* @param string $method |
71
|
|
|
*/ |
72
|
|
|
protected function evaluate($method) |
73
|
|
|
{ |
74
|
|
|
$annotations = $this->inspector->getMethodAnnotations($method); |
75
|
|
|
|
76
|
|
|
if (! $annotations->hasAnnotation('@inject')) { |
77
|
|
|
return; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
$annotation = $annotations->getAnnotation('@inject'); |
81
|
|
|
$param = $annotation->getValue(); |
82
|
|
|
|
83
|
|
|
$this->inspector |
84
|
|
|
->getReflection() |
85
|
|
|
->getMethod($method) |
86
|
|
|
->invokeArgs($this->object, [$this->getContainer()->get($param)]) |
87
|
|
|
; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|