Completed
Push — master ( e9cff8...bf916e )
by Phil
01:58
created

ArgumentResolverTrait::resolveArguments()   D

Complexity

Conditions 9
Paths 9

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 31
Code Lines 16

Code Coverage

Tests 19
CRAP Score 9

Importance

Changes 7
Bugs 2 Features 1
Metric Value
c 7
b 2
f 1
dl 0
loc 31
ccs 19
cts 19
cp 1
rs 4.909
cc 9
eloc 16
nc 9
nop 1
crap 9
1
<?php
2
3
namespace League\Container\Argument;
4
5
use League\Container\Exception\NotFoundException;
6
use League\Container\ReflectionContainer;
7
use ReflectionFunctionAbstract;
8
use ReflectionParameter;
9
10
trait ArgumentResolverTrait
11
{
12
    /**
13
     * [email protected]}
14
     */
15 72
    public function resolveArguments(array $arguments)
16
    {
17 72
        foreach ($arguments as &$arg) {
18 66
            if ($arg instanceof RawArgumentInterface) {
19 6
                $arg = $arg->getValue();
20 6
                continue;
21
            }
22
23 60
            if (! is_string($arg)) {
24 6
                 continue;
25
            }
26
27 57
            $container = $this->getContainer();
28
29 57
            if (is_null($container) && $this instanceof ReflectionContainer) {
30 12
                $container = $this;
31 12
            }
32
33 57
            if (! is_null($container) && $container->has($arg)) {
34 48
                $arg = $container->get($arg);
35
36 48
                if ($arg instanceof RawArgumentInterface) {
37 3
                    $arg = $arg->getValue();
38 3
                }
39
40 48
                continue;
41
            }
42 72
        }
43
44 72
        return $arguments;
45
    }
46
47
    /**
48
     * [email protected]}
49
     */
50
    public function reflectArguments(ReflectionFunctionAbstract $method, array $args = [])
51
    {
52 24
        $arguments = array_map(function (ReflectionParameter $param) use ($method, $args) {
53 24
            $name  = $param->getName();
54 24
            $class = $param->getClass();
55
56 24
            if (array_key_exists($name, $args)) {
57 3
                return $args[$name];
58
            }
59
60 21
            if (! is_null($class)) {
61 18
                return $class->getName();
62
            }
63
64 6
            if ($param->isDefaultValueAvailable()) {
65 3
                return $param->getDefaultValue();
66
            }
67
68 3
            throw new NotFoundException(sprintf(
69 3
                'Unable to resolve a value for parameter (%s) in the function/method (%s)',
70 3
                $name,
71 3
                $method->getName()
72 3
            ));
73 24
        }, $method->getParameters());
74
75 21
        return $this->resolveArguments($arguments);
76
    }
77
78
    /**
79
     * @return ContainerInterface
80
     */
81
    abstract public function getContainer();
82
}
83