Passed
Push — misc/rename-event-directory ( b489af )
by Chema
04:28
created

ConfigurableEventDispatcher::dispatch()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 4
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Event\Dispatcher;
6
7
use function get_class;
8
use function is_callable;
9
10
final class ConfigurableEventDispatcher implements EventDispatcherInterface
11
{
12
    /** @var array<callable> */
13
    private array $genericListeners = [];
14
15
    /** @var array<class-string,list<callable>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<class-string,list<callable>> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in array<class-string,list<callable>>.
Loading history...
16
    private array $specificListeners = [];
17
18
    public function __construct()
19
    {
20
    }
21
22
    /**
23
     * @param list<callable> $genericListeners
24
     */
25 17
    public function registerGenericListeners(array $genericListeners): void
26
    {
27 17
        $this->genericListeners = $genericListeners;
28
    }
29
    /**
30
     * @param class-string $event
31
     */
32 4
    public function registerSpecificListener(string $event, callable $listener): void
33
    {
34 4
        $this->specificListeners[$event][] = $listener;
35
    }
36
37
    public function dispatchAll(array $events): void
38
    {
39
        foreach ($events as $event) {
40
            $this->dispatch($event);
41
        }
42
    }
43
44 63
    public function dispatch(object $event): void
45
    {
46 63
        foreach ($this->genericListeners as $listener) {
47 5
            $this->notifyListener($listener, $event);
48
        }
49
50 63
        foreach ($this->specificListeners[get_class($event)] ?? [] as $listener) {
51 10
            $this->notifyListener($listener, $event);
52
        }
53
    }
54
55 15
    private function notifyListener(callable $listener, object $event): void
56
    {
57
        /** @psalm-suppress MixedAssignment */
58 15
        $result = $listener($event);
59 15
        if (is_callable($result)) {
60
            $result($event);
61
        }
62
    }
63
}
64