|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yiisoft\EventDispatcher\Provider; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\EventDispatcher\ListenerProviderInterface; |
|
6
|
|
|
|
|
7
|
|
|
use function array_values; |
|
8
|
|
|
use function class_implements; |
|
9
|
|
|
use function class_parents; |
|
10
|
|
|
use function get_class; |
|
11
|
|
|
|
|
12
|
|
|
final class ConcreteProvider implements ListenerProviderInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var callable[] |
|
16
|
|
|
*/ |
|
17
|
|
|
private array $listeners = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param object $event |
|
21
|
|
|
* @return iterable<callable> |
|
22
|
|
|
*/ |
|
23
|
9 |
|
public function getListenersForEvent(object $event): iterable |
|
24
|
|
|
{ |
|
25
|
9 |
|
yield from $this->listenersFor(get_class($event)); |
|
26
|
8 |
|
yield from $this->listenersFor(...array_values(class_parents($event))); |
|
27
|
8 |
|
yield from $this->listenersFor(...array_values(class_implements($event))); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Attach an event handler for the given event name |
|
32
|
|
|
* |
|
33
|
|
|
* @param string $eventName |
|
34
|
|
|
* @param callable $listener |
|
35
|
|
|
*/ |
|
36
|
9 |
|
public function attach(string $eventName, callable $listener): void |
|
37
|
|
|
{ |
|
38
|
9 |
|
$this->listeners[$eventName][] = $listener; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Detach all event handlers registered for an interface |
|
43
|
|
|
* |
|
44
|
|
|
* @param string $eventName |
|
45
|
|
|
*/ |
|
46
|
1 |
|
public function detach(string $eventName): void |
|
47
|
|
|
{ |
|
48
|
1 |
|
unset($this->listeners[$eventName]); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string ...$eventNames |
|
53
|
|
|
* @return iterable<callable> |
|
54
|
|
|
*/ |
|
55
|
9 |
|
private function listenersFor(string ...$eventNames): iterable |
|
56
|
|
|
{ |
|
57
|
9 |
|
foreach ($eventNames as $name) { |
|
58
|
9 |
|
if (isset($this->listeners[$name])) { |
|
59
|
8 |
|
yield from $this->listeners[$name]; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|