Completed
Pull Request — master (#109)
by Andreas
12:44 queued 10:31
created

ReflectionContainer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 93.1%

Importance

Changes 7
Bugs 3 Features 2
Metric Value
wmc 10
c 7
b 3
f 2
lcom 1
cbo 3
dl 0
loc 72
ccs 27
cts 29
cp 0.931
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 19 3
A has() 0 4 1
B call() 0 26 6
1
<?php
2
3
namespace League\Container;
4
5
use League\Container\Argument\ArgumentResolverInterface;
6
use League\Container\Argument\ArgumentResolverTrait;
7
use League\Container\Exception\NotFoundException;
8
use ReflectionClass;
9
use ReflectionFunction;
10
use ReflectionMethod;
11
12
class ReflectionContainer implements
13
    ArgumentResolverInterface,
14
    ImmutableContainerInterface
15
{
16
    use ArgumentResolverTrait;
17
    use ImmutableContainerAwareTrait;
18
19
    /**
20
     * {@inheritdoc}
21
     */
22 30
    public function get($alias, array $args = [])
23
    {
24 30
        if (! $this->has($alias)) {
25 3
            throw new NotFoundException(
26 3
                sprintf('Alias (%s) is not an existing class and therefore cannot be resolved', $alias)
27 3
            );
28
        }
29
30 27
        $reflector = new ReflectionClass($alias);
31 27
        $construct = $reflector->getConstructor();
32
33 27
        if ($construct === null) {
34 18
            return new $alias;
35
        }
36
37 15
        return $reflector->newInstanceArgs(
38 15
            $this->reflectArguments($construct, $args)
39 15
        );
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 36
    public function has($alias)
46
    {
47 36
        return class_exists($alias);
48
    }
49
50
    /**
51
     * Invoke a callable via the container.
52
     *
53
     * @param  callable $callable
54
     * @param  array    $args
55
     * @return mixed
56
     */
57 15
    public function call(callable $callable, array $args = [])
58
    {
59 15
        if (is_string($callable) && strpos($callable, '::') !== false) {
60 3
            $callable = explode('::', $callable);
61 3
        }
62
63 15
        if (is_array($callable)) {
64 9
            $reflection = new ReflectionMethod($callable[0], $callable[1]);
65
66 9
            if ($reflection->isStatic()) {
67 3
                $callable[0] = null;
68 3
            }
69
70 9
            return $reflection->invokeArgs($callable[0], $this->reflectArguments($reflection, $args));
71
        }
72
73 6
        if (is_object($callable)) {
74 6
            $reflection = new ReflectionMethod($callable, '__invoke');
75
76 6
            return $reflection->invokeArgs($callable, $this->reflectArguments($reflection, $args));
77
        }
78
79
        $reflection = new ReflectionFunction($callable);
80
81
        return $reflection->invokeArgs($this->reflectArguments($reflection, $args));
82
    }
83
}
84