Passed
Push — feature/add-container-protect-... ( b82e87 )
by Chema
04:32
created

ConfigurableEventDispatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 2
cc 1
rs 10
ccs 1
cts 1
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Event\Dispatcher;
6
7
use function get_class;
8
9
final class ConfigurableEventDispatcher implements EventDispatcherInterface
10
{
11
    /** @var array<callable> */
12
    private array $genericListeners = [];
13
14
    /** @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...
15
    private array $specificListeners = [];
16
17 13
    public function __construct()
18
    {
19 13
    }
20
21
    /**
22
     * @param list<callable> $genericListeners
23
     */
24 13
    public function registerGenericListeners(array $genericListeners): void
25
    {
26 13
        $this->genericListeners = $genericListeners;
27
    }
28
    /**
29
     * @param class-string $event
30
     */
31 6
    public function registerSpecificListener(string $event, callable $listener): void
32
    {
33 6
        $this->specificListeners[$event][] = $listener;
34
    }
35
36 33
    public function dispatch(object $event): void
37
    {
38 33
        foreach ($this->genericListeners as $listener) {
39 20
            $this->notifyListener($listener, $event);
40
        }
41
42 33
        foreach ($this->specificListeners[get_class($event)] ?? [] as $listener) {
43 6
            $this->notifyListener($listener, $event);
44
        }
45
    }
46
47 26
    private function notifyListener(callable $listener, object $event): void
48
    {
49 26
        $listener($event);
50
    }
51
}
52