|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace mindplay\walkway; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use Interop\Container\ContainerInterface; |
|
7
|
|
|
use ReflectionFunction; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* This is an invoker implementation that attempts to resolve parameters directly |
|
11
|
|
|
* provided first, then attempts to have a dependency injection container resolve |
|
12
|
|
|
* the argument by type. |
|
13
|
|
|
* |
|
14
|
|
|
* This provides integration with a number of DI containers via `container-interop`: |
|
15
|
|
|
* |
|
16
|
|
|
* https://github.com/container-interop/container-interop#compatible-projects |
|
17
|
|
|
* |
|
18
|
|
|
* To use this, you will need to install the `container-interop/container-interop` |
|
19
|
|
|
* Composer package. |
|
20
|
|
|
*/ |
|
21
|
|
|
class InteropInvoker implements InvokerInterface |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* @var ContainerInterface |
|
25
|
|
|
*/ |
|
26
|
|
|
protected $container; |
|
27
|
|
|
|
|
28
|
1 |
|
public function __construct(ContainerInterface $container) |
|
29
|
|
|
{ |
|
30
|
1 |
|
$this->container = $container; |
|
31
|
1 |
|
} |
|
32
|
|
|
|
|
33
|
1 |
|
public function invoke(Closure $func, array $params) |
|
34
|
|
|
{ |
|
35
|
1 |
|
$func_ref = new ReflectionFunction($func); |
|
36
|
1 |
|
$param_refs = $func_ref->getParameters(); |
|
37
|
|
|
|
|
38
|
1 |
|
$args = array(); |
|
39
|
|
|
|
|
40
|
1 |
|
foreach ($param_refs as $param_ref) { |
|
41
|
1 |
|
if (array_key_exists($param_ref->name, $params)) { |
|
42
|
1 |
|
$args[] = $params[$param_ref->name]; |
|
43
|
|
|
|
|
44
|
1 |
|
continue; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
1 |
|
$argument_type = $param_ref->getClass(); |
|
48
|
|
|
|
|
49
|
1 |
|
if ($argument_type && $this->container->has($argument_type->name)) { |
|
50
|
1 |
|
$args[] = $this->container->get($argument_type->name); |
|
51
|
|
|
|
|
52
|
1 |
|
continue; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
if ($param_ref->isDefaultValueAvailable()) { |
|
56
|
1 |
|
$args[] = $param_ref->getDefaultValue(); |
|
57
|
|
|
|
|
58
|
1 |
|
continue; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
throw new InvocationException("missing parameter: \${$param_ref->name}", $func); |
|
62
|
1 |
|
} |
|
63
|
|
|
|
|
64
|
1 |
|
return call_user_func_array($func, $args); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|