1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Ray.Di package. |
4
|
|
|
* |
5
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
6
|
|
|
*/ |
7
|
|
|
namespace Ray\Di; |
8
|
|
|
|
9
|
|
|
use Doctrine\Common\Annotations\Reader; |
10
|
|
|
use Ray\Aop\Annotation\AbstractAssisted; |
11
|
|
|
use Ray\Aop\MethodInterceptor; |
12
|
|
|
use Ray\Aop\MethodInvocation; |
13
|
|
|
use Ray\Aop\ReflectionMethod; |
14
|
|
|
|
15
|
|
|
final class AssistedInterceptor implements MethodInterceptor |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var InjectorInterface |
19
|
|
|
*/ |
20
|
|
|
private $injector; |
21
|
|
|
|
22
|
2 |
|
public function __construct(InjectorInterface $injector) |
23
|
|
|
{ |
24
|
2 |
|
$this->injector = $injector; |
25
|
2 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Intercepts any method and injects instances of the missing arguments |
29
|
|
|
* when they are type hinted |
30
|
|
|
*/ |
31
|
2 |
|
public function invoke(MethodInvocation $invocation) |
32
|
|
|
{ |
33
|
2 |
|
$method = $invocation->getMethod(); |
34
|
2 |
|
$assisted = $method->getAnnotation('Ray\Di\Di\Assisted'); |
35
|
|
|
/* @var \Ray\Di\Di\Assisted $assisted */ |
36
|
2 |
|
$parameters = $method->getParameters(); |
37
|
2 |
|
$arguments = $invocation->getArguments()->getArrayCopy(); |
38
|
2 |
|
$cntArgs = count($arguments); |
39
|
2 |
|
foreach ($parameters as $pos => $parameter) { |
40
|
2 |
|
if ($pos < $cntArgs || ! $assisted || ! in_array($parameter->getName(), $assisted->values)) { |
41
|
2 |
|
continue; |
42
|
|
|
} |
43
|
2 |
|
$hint = $parameter->getClass(); |
44
|
2 |
|
$interface = $hint ? $hint->getName() : ''; |
45
|
2 |
|
$name = $this->getName($method, $parameter); |
46
|
2 |
|
$arguments[] = $this->injector->getInstance($interface, $name); |
47
|
2 |
|
} |
48
|
2 |
|
$invocation->getArguments()->exchangeArray($arguments); |
49
|
|
|
|
50
|
2 |
|
return $invocation->proceed(); |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
private function getName(ReflectionMethod $method, \ReflectionParameter $parameter) |
54
|
|
|
{ |
55
|
2 |
|
$named = $method->getAnnotation('Ray\Di\Di\Named'); |
56
|
2 |
|
if (! $named) { |
57
|
1 |
|
return Name::ANY; |
58
|
|
|
} |
59
|
1 |
|
parse_str($named->value, $names); |
60
|
1 |
|
$paramName = $parameter->getName(); |
61
|
1 |
|
if (isset($names[$paramName])) { |
62
|
1 |
|
return $names[$paramName]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return Name::ANY; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|