Completed
Pull Request — 2.x (#198)
by Akihito
10:27 queued 09:16
created

Arguments::getDefaultValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
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 64
    public function __construct(\ReflectionMethod $method, Name $name)
18
    {
19 64
        $parameters = $method->getParameters();
20 64
        foreach ($parameters as $parameter) {
21 64
            $this->arguments[] = new Argument($parameter, $name($parameter));
22
        }
23 64
    }
24
25
    /**
26
     * Return arguments
27
     *
28
     * @throws Exception\Unbound
29
     *
30
     * @return Argument[]
31
     */
32 38
    public function inject(Container $container) : array
33
    {
34 38
        $parameters = $this->arguments;
35 38
        foreach ($parameters as &$parameter) {
36 38
            $parameter = $this->getParameter($container, $parameter);
37
        }
38
39 36
        return $parameters;
40
    }
41
42
    /**
43
     * @throws Unbound
44
     */
45 38
    private function getParameter(Container $container, Argument $argument)
46
    {
47 38
        $this->bindInjectionPoint($container, $argument);
48
        try {
49 38
            return $container->getDependency((string) $argument);
50 13
        } catch (Unbound $e) {
51 13
            if ($argument->isDefaultAvailable()) {
52 13
                return $argument->getDefaultValue();
53 7
            }
54
55
            throw new Unbound($argument->getMeta(), 0, $e);
56 7
        }
57
    }
58
59
    private function bindInjectionPoint(Container $container, Argument $argument) : void
60
    {
61
        $isSelf = (string) $argument === InjectionPointInterface::class . '-' . Name::ANY;
62
        if ($isSelf) {
63 13
            return;
64
        }
65 13
        (new Bind($container, InjectionPointInterface::class))->toInstance(new InjectionPoint($argument->get(), new AnnotationReader));
66 7
    }
67
}
68