1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ray\Di; |
6
|
|
|
|
7
|
|
|
use Ray\Aop\MethodInterceptor; |
8
|
|
|
use Ray\Aop\MethodInvocation; |
9
|
|
|
use Ray\Di\Di\Inject; |
10
|
|
|
use Ray\Di\Di\Named; |
11
|
|
|
use ReflectionParameter; |
12
|
|
|
|
13
|
|
|
use function assert; |
14
|
|
|
use function call_user_func_array; |
15
|
|
|
|
16
|
|
|
final class ParamInjectInterceptor implements MethodInterceptor |
17
|
|
|
{ |
18
|
|
|
/** @var InjectorInterface */ |
19
|
|
|
private $injector; |
20
|
|
|
|
21
|
|
|
/** @var MethodInvocationProvider */ |
22
|
|
|
private $methodInvocationProvider; |
23
|
|
|
|
24
|
|
|
public function __construct(InjectorInterface $injector, MethodInvocationProvider $methodInvocationProvider) |
25
|
|
|
{ |
26
|
|
|
$this->injector = $injector; |
27
|
|
|
$this->methodInvocationProvider = $methodInvocationProvider; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function invoke(MethodInvocation $invocation) |
31
|
|
|
{ |
32
|
|
|
$params = $invocation->getMethod()->getParameters(); |
33
|
|
|
$namedArguments = $invocation->getNamedArguments()->getArrayCopy(); |
|
|
|
|
34
|
|
|
$injectedParams = []; |
35
|
|
|
foreach ($params as $param) { |
36
|
|
|
$attributes = $param->getAttributes(Inject::class); |
37
|
|
|
if (isset($attributes[0])) { |
38
|
|
|
$injectedParams[$param->getName()] = $this->getDependency($param); |
|
|
|
|
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$args = $injectedParams + $params; |
43
|
|
|
|
44
|
|
|
return call_user_func_array([$invocation->getThis(), $invocation->getMethod()->getName()], $args); |
|
|
|
|
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function getDependencies(array $params) |
|
|
|
|
48
|
|
|
{ |
49
|
|
|
$params = []; |
50
|
|
|
foreach ($params as $param) { |
51
|
|
|
$dependecy = $this->getDependency($param); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function getDependency(ReflectionParameter $param) |
56
|
|
|
{ |
57
|
|
|
$named = $this->getName($param); |
58
|
|
|
$interface = $param->getType()->getName(); |
59
|
|
|
|
60
|
|
|
return $this->injector->getInstance($interface, $named); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function getName(ReflectionParameter $param): string |
64
|
|
|
{ |
65
|
|
|
$attributes = $param->getAttributes(Named::class); |
66
|
|
|
if (isset($attributes[0])) { |
67
|
|
|
$named = $attributes[0]->newInstance(); |
68
|
|
|
assert($named instanceof Named); |
69
|
|
|
|
70
|
|
|
return $named->value; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return ''; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVar
assignment in line 1 and the$higher
assignment in line 2 are dead. The first because$myVar
is never used and the second because$higher
is always overwritten for every possible time line.