Completed
Push — refactor ( fcb4ff...1d251b )
by Akihito
01:15
created

Arguments::getDefaultValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di;
6
7
use Doctrine\Common\Annotations\AnnotationReader;
8
use Ray\Di\Exception\Unbound;
9
10
final class Arguments
11
{
12
    /**
13
     * @var Argument[]
14
     */
15
    private $arguments = [];
16
17
    public function __construct(\ReflectionMethod $method, Name $name)
18
    {
19
        $parameters = $method->getParameters();
20
        foreach ($parameters as $parameter) {
21 64
            $this->arguments[] = new Argument($parameter, $name($parameter));
22
        }
23 64
    }
24 64
25 64
    /**
26
     * Return arguments
27 64
     *
28
     * @throws Exception\Unbound
29
     *
30
     * @return Argument[]
31
     */
32
    public function inject(Container $container) : array
33
    {
34
        $parameters = $this->arguments;
35
        foreach ($parameters as &$parameter) {
36
            $parameter = $this->getParameter($container, $parameter);
37
        }
38 38
39
        return $parameters;
40 38
    }
41 38
42 38
    /**
43
     * @throws Unbound
44
     */
45 36
    private function getParameter(Container $container, Argument $argument)
46
    {
47
        $this->bindInjectionPoint($container, $argument);
48
        try {
49
            return $container->getDependency((string) $argument);
50
        } catch (Unbound $e) {
51
            if ($argument->isDefaultAvailable()) {
52
                return $argument->getDefaultValue();
53 38
            }
54
55 38
            throw new Unbound($argument->getMeta(), 0, $e);
56
        }
57 38
    }
58 13
59 13
    private function bindInjectionPoint(Container $container, Argument $argument) : void
60 13
    {
61 7
        $isSelf = (string) $argument === InjectionPointInterface::class . '-' . Name::ANY;
62
        if ($isSelf) {
63 7
            return;
64
        }
65
        (new Bind($container, InjectionPointInterface::class))->toInstance(new InjectionPoint($argument->get(), new AnnotationReader));
66
    }
67
}
68