1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace League\Tactician\Bundle\DependencyInjection\HandlerMapping; |
5
|
|
|
|
6
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
7
|
|
|
use Symfony\Component\DependencyInjection\Definition; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Routes commands based on typehints in the handler. |
12
|
|
|
* |
13
|
|
|
* If your handler has a public method with a single, non-scalar, no-interface type hinted |
14
|
|
|
* parameter, we'll assume that typehint is a command and route it to this |
15
|
|
|
* service definition as the handler. |
16
|
|
|
* |
17
|
|
|
* So, a class like this: |
18
|
|
|
* |
19
|
|
|
* class MyHandler |
20
|
|
|
* { |
21
|
|
|
* public function handle(RegisterUser $command) {...} |
22
|
|
|
* private function foobar(SomeObject $obj) {...} |
23
|
|
|
* public function checkThings(OtherObject $obj, WhatObject $obj2) |
24
|
|
|
* public function setADependency(ManagerInterface $interface) {...} |
25
|
|
|
* } |
26
|
|
|
* |
27
|
|
|
* would have RegisterUser routed to it, but not SomeObject (because it's |
28
|
|
|
* used in a private method), not OtherObject or WhatObject (because they |
29
|
|
|
* don't appear as the only parameter) and not setADependency (because it |
30
|
|
|
* has an interface type hinted parameter). |
31
|
|
|
*/ |
32
|
|
|
final class TypeHintMapping extends TagBasedMapping |
33
|
|
|
{ |
34
|
78 |
|
protected function isSupported(ContainerBuilder $container, Definition $definition, array $tagAttributes): bool |
35
|
|
|
{ |
36
|
78 |
|
return isset($tagAttributes['typehints']) && $tagAttributes['typehints'] === true; |
37
|
|
|
} |
38
|
|
|
|
39
|
51 |
|
protected function findCommandsForService(ContainerBuilder $container, Definition $definition, array $tagAttributes): array |
40
|
|
|
{ |
41
|
51 |
|
$results = []; |
42
|
|
|
|
43
|
51 |
|
$reflClass = new ReflectionClass($container->getParameterBag()->resolveValue($definition->getClass())); |
44
|
|
|
|
45
|
51 |
|
foreach ($reflClass->getMethods() as $method) { |
46
|
|
|
|
47
|
51 |
|
if (!$method->isPublic() |
48
|
48 |
|
|| $method->isConstructor() |
49
|
45 |
|
|| $method->isStatic() |
50
|
42 |
|
|| $method->isAbstract() |
51
|
39 |
|
|| $method->isVariadic() |
52
|
51 |
|
|| $method->getNumberOfParameters() !== 1 |
53
|
|
|
) { |
54
|
27 |
|
continue; |
55
|
|
|
} |
56
|
|
|
|
57
|
36 |
|
$parameter = $method->getParameters()[0]; |
58
|
36 |
|
if (!$parameter->hasType() |
59
|
33 |
|
|| $parameter->getType()->isBuiltin() |
60
|
36 |
|
|| $parameter->getClass()->isInterface() |
61
|
|
|
) { |
62
|
9 |
|
continue; |
63
|
|
|
} |
64
|
|
|
|
65
|
27 |
|
$results[] = (string)$parameter->getType(); |
66
|
|
|
} |
67
|
|
|
|
68
|
51 |
|
return $results; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|