Completed
Push — 2.x ( e0ffa3...2bc12f )
by Akihito
03:04
created

Arguments::getDefaultValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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 array<int, mixed>
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
31
     */
32
    public function inject(Container $container) : array
33
    {
34
        $parameters = [];
35
        foreach ($this->arguments as $parameter) {
36
            /** @psalm-suppress MixedAssignment */
37
            $parameters[] = $this->getParameter($container, $parameter);
38 38
        }
39
40 38
        return $parameters;
41 38
    }
42 38
43
    /**
44
     * @throws Unbound
45 36
     *
46
     * @return mixed
47
     */
48
    private function getParameter(Container $container, Argument $argument)
49
    {
50
        $this->bindInjectionPoint($container, $argument);
51
        try {
52
            return $container->getDependency((string) $argument);
53 38
        } catch (Unbound $e) {
54
            if ($argument->isDefaultAvailable()) {
55 38
                return $argument->getDefaultValue();
56
            }
57 38
58 13
            throw new Unbound($argument->getMeta(), 0, $e);
59 13
        }
60 13
    }
61 7
62
    private function bindInjectionPoint(Container $container, Argument $argument) : void
63 7
    {
64
        $isSelf = (string) $argument === InjectionPointInterface::class . '-' . Name::ANY;
65
        if ($isSelf) {
66
            return;
67
        }
68
        (new Bind($container, InjectionPointInterface::class))->toInstance(new InjectionPoint($argument->get(), new AnnotationReader));
69
    }
70
}
71