Dispatcher::getOrderedDispatcherArguments()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 20
rs 9.6111
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
The expression return $this->dispatcher could return the type null which is incompatible with the type-hinted return Symfony\Component\EventD...ventDispatcherInterface. Consider adding an additional type-check to rule them out.
Loading history...
68
    }
69
}
70