|
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>> */ |
|
|
|
|
|
|
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
|
8 |
|
$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
|
18 |
|
private function notifyListener(callable $listener, object $event): void |
|
56
|
|
|
{ |
|
57
|
|
|
/** @psalm-suppress MixedAssignment */ |
|
58
|
18 |
|
$result = $listener($event); |
|
59
|
18 |
|
if (is_callable($result)) { |
|
60
|
|
|
$result($event); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|