1 | <?php |
||
2 | |||
3 | namespace RemotelyLiving\PHPDNS\Observability\Traits; |
||
4 | |||
5 | use LogicException; |
||
6 | use ReflectionClass; |
||
7 | use ReflectionMethod; |
||
8 | use RemotelyLiving\PHPDNS\Observability\Events\ObservableEventAbstract; |
||
9 | use Symfony\Component\EventDispatcher\EventDispatcher; |
||
10 | use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
||
11 | use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
||
12 | |||
13 | use function call_user_func_array; |
||
14 | |||
15 | trait Dispatcher |
||
16 | { |
||
17 | private ?EventDispatcherInterface $dispatcher = null; |
||
18 | |||
19 | public function setDispatcher(EventDispatcherInterface $dispatcher): void |
||
20 | { |
||
21 | $this->dispatcher = $dispatcher; |
||
22 | } |
||
23 | |||
24 | public function addSubscriber(EventSubscriberInterface $subscriber): void |
||
25 | { |
||
26 | $this->getDispatcher()->addSubscriber($subscriber); |
||
27 | } |
||
28 | |||
29 | public function addListener(string $eventName, callable $listener, int $priority = 0): void |
||
30 | { |
||
31 | $this->getDispatcher()->addListener($eventName, $listener, $priority); |
||
32 | } |
||
33 | |||
34 | public function dispatch(ObservableEventAbstract $event): void |
||
35 | { |
||
36 | call_user_func_array([$this->getDispatcher(), 'dispatch'], $this->getOrderedDispatcherArguments($event)); |
||
37 | } |
||
38 | |||
39 | private function getOrderedDispatcherArguments(ObservableEventAbstract $event): array |
||
40 | { |
||
41 | $reflection = new ReflectionClass($this->getDispatcher()); |
||
42 | $args = []; |
||
43 | |||
44 | foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { |
||
45 | if ($method->getName() !== 'dispatch') { |
||
46 | continue; |
||
47 | } |
||
48 | // @codeCoverageIgnoreStart |
||
49 | foreach ($method->getParameters() as $parameter) { |
||
50 | $args = ($parameter->getName() === 'event') |
||
51 | ? [$event, $event::getName()] |
||
52 | : [$event::getName(), $event]; |
||
53 | break; |
||
54 | } |
||
55 | // @codeCoverageIgnoreEnd |
||
56 | } |
||
57 | |||
58 | return $args; |
||
59 | } |
||
60 | |||
61 | private function getDispatcher(): EventDispatcherInterface |
||
62 | { |
||
63 | if ($this->dispatcher === null) { |
||
64 | $this->dispatcher = new EventDispatcher(); |
||
65 | } |
||
66 | |||
67 | return $this->dispatcher; |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
68 | } |
||
69 | } |
||
70 |