|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\Events\Processor; |
|
6
|
|
|
|
|
7
|
|
|
use Spiral\Events\Exception\InvalidArgumentException; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractProcessor implements ProcessorInterface |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Get event class list from the listener method signature. |
|
13
|
|
|
* The signature must have only one parameter with Event class type. |
|
14
|
|
|
* |
|
15
|
|
|
* @return class-string[] |
|
|
|
|
|
|
16
|
|
|
*/ |
|
17
|
7 |
|
protected function getEventFromTypeDeclaration(\ReflectionMethod $method): array |
|
18
|
|
|
{ |
|
19
|
7 |
|
if ($method->getNumberOfParameters() > 1) { |
|
20
|
|
|
throw $this->badClassMethod($method->class, $method->getName()); |
|
21
|
|
|
} |
|
22
|
7 |
|
$type = $method->getParameters()[0]->getType(); |
|
23
|
|
|
|
|
24
|
|
|
/** @var \ReflectionNamedType[] $eventTypes */ |
|
25
|
7 |
|
$eventTypes = match (true) { |
|
26
|
7 |
|
$type instanceof \ReflectionNamedType => [$type], |
|
27
|
1 |
|
$type instanceof \ReflectionUnionType => $type->getTypes(), |
|
|
|
|
|
|
28
|
|
|
default => throw $this->badClassMethod($method->class, $method->getName()), |
|
29
|
7 |
|
}; |
|
30
|
|
|
|
|
31
|
7 |
|
$result = []; |
|
32
|
7 |
|
foreach ($eventTypes as $type) { |
|
33
|
7 |
|
if ($type->isBuiltin()) { |
|
34
|
|
|
continue; |
|
35
|
|
|
} |
|
36
|
7 |
|
$result[] = $type->getName(); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
7 |
|
return $result; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param class-string $class |
|
|
|
|
|
|
44
|
|
|
*/ |
|
45
|
10 |
|
protected function getMethod(string $class, string $name): \ReflectionMethod |
|
46
|
|
|
{ |
|
47
|
|
|
try { |
|
48
|
10 |
|
return new \ReflectionMethod($class, $name); |
|
49
|
|
|
} catch (\ReflectionException) { |
|
50
|
|
|
throw $this->badClassMethod($class, $name); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @param class-string $class |
|
|
|
|
|
|
56
|
|
|
*/ |
|
57
|
|
|
private function badClassMethod(string $class, string $name): InvalidArgumentException |
|
58
|
|
|
{ |
|
59
|
|
|
return new InvalidArgumentException( |
|
60
|
|
|
\sprintf( |
|
61
|
|
|
'`%s::%s` must contain only one parameter with event class type that listener will listen.', |
|
62
|
|
|
$class, |
|
63
|
|
|
$name |
|
64
|
|
|
) |
|
65
|
|
|
); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|