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