Completed
Pull Request — master (#126)
by Phil
02:35
created

ReflectionContainer::has()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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