Completed
Push — master ( 696114...b35b16 )
by Phil
05:53 queued 02:05
created

ReflectionContainer::has()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
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 30
    public function get($id, array $args = [])
21
    {
22 30
        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 27
        $reflector = new ReflectionClass($id);
29 27
        $construct = $reflector->getConstructor();
30
31 27
        if ($construct === null) {
32 21
            return new $id;
33
        }
34
35 18
        return $reflector->newInstanceArgs(
36 18
            $this->reflectArguments($construct, $args)
37
        );
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 36
    public function has($id): bool
44
    {
45 36
        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
            if (is_string($callable[0])) {
64 3
                $callable[0] = $this->getContainer()->get($callable[0]);
65
            }
66
67 9
            $reflection = new ReflectionMethod($callable[0], $callable[1]);
68
69 9
            if ($reflection->isStatic()) {
70 3
                $callable[0] = null;
71
            }
72
73 9
            return $reflection->invokeArgs($callable[0], $this->reflectArguments($reflection, $args));
74
        }
75
76 6
        if (is_object($callable)) {
77 6
            $reflection = new ReflectionMethod($callable, '__invoke');
78
79 6
            return $reflection->invokeArgs($callable, $this->reflectArguments($reflection, $args));
80
        }
81
82
        $reflection = new ReflectionFunction($callable);
83
84
        return $reflection->invokeArgs($this->reflectArguments($reflection, $args));
85
    }
86
}
87