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

ArgumentResolverTrait   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 10
Bugs 3 Features 2
Metric Value
wmc 13
c 10
b 3
f 2
lcom 0
cbo 2
dl 0
loc 73
ccs 35
cts 35
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B reflectArguments() 0 27 4
getContainer() 0 1 ?
D resolveArguments() 0 31 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
     * {@inheritdoc}
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
     * {@inheritdoc}
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