|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace OniBus\Handler\ClassMethod\Extractor; |
|
5
|
|
|
|
|
6
|
|
|
use OniBus\Handler\ClassMethod\ClassMethod; |
|
7
|
|
|
use OniBus\Handler\ClassMethod\ClassMethodExtractor; |
|
8
|
|
|
use ReflectionClass; |
|
9
|
|
|
use ReflectionException; |
|
10
|
|
|
use ReflectionMethod; |
|
11
|
|
|
use ReflectionNamedType; |
|
12
|
|
|
|
|
13
|
|
|
class MethodFirstParameterExtractor implements ClassMethodExtractor |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var string |
|
17
|
|
|
*/ |
|
18
|
|
|
protected $method; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $handlersFQCN; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(string $method, array $handlersFQCN = []) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->method = $method; |
|
28
|
|
|
$this->handlersFQCN = $handlersFQCN; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @inheritDoc |
|
33
|
|
|
*/ |
|
34
|
|
|
public function extractClassMethods(): array |
|
35
|
|
|
{ |
|
36
|
|
|
$mapped = []; |
|
37
|
|
|
foreach ($this->handlersFQCN as $class) { |
|
38
|
|
|
$mapped = array_merge($mapped, $this->getHandlers($class)); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $mapped; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* @param string $class |
|
46
|
|
|
* @return ClassMethod[] |
|
47
|
|
|
* @throws ReflectionException |
|
48
|
|
|
*/ |
|
49
|
|
|
protected function getHandlers(string $class): array |
|
50
|
|
|
{ |
|
51
|
|
|
$handlers = []; |
|
52
|
|
|
if (!class_exists($class)) { |
|
53
|
|
|
return $handlers; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
$reflectionClass = new ReflectionClass($class); |
|
57
|
|
|
foreach ($reflectionClass->getMethods() as $method) { |
|
58
|
|
|
if ($method->getName() !== $this->method) { |
|
59
|
|
|
continue; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$firstParameterTypeHint = $this->firstParameterTypeHint($method); |
|
63
|
|
|
if (!is_null($firstParameterTypeHint)) { |
|
64
|
|
|
$handlers[] = new ClassMethod($firstParameterTypeHint, $class, $method->getName()); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $handlers; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function firstParameterTypeHint(ReflectionMethod $method): ?string |
|
72
|
|
|
{ |
|
73
|
|
|
if (!$method->getNumberOfParameters()) { |
|
74
|
|
|
return null; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
$parameterType = $method->getParameters()[0]->getType(); |
|
78
|
|
|
if (! $parameterType instanceof ReflectionNamedType) { |
|
79
|
|
|
return null; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
if ($parameterType->isBuiltin()) { |
|
83
|
|
|
return null; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
return ltrim($parameterType->getName(), "?"); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|