Completed
Push — assisted ( 82d8ca...d6f990 )
by Akihito
03:53
created

AssistedInterceptor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 96.43%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 10
c 3
b 0
f 1
lcom 1
cbo 4
dl 0
loc 53
ccs 27
cts 28
cp 0.9643
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B invoke() 0 21 6
A getName() 0 14 3
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