-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListenerProvider.php
87 lines (74 loc) · 2.31 KB
/
ListenerProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\EventDispatcher;
use Psr\EventDispatcher\ListenerProviderInterface;
/**
* Supports
* - Event Names like "event.name"
* - Listener Priorities
* - Event Subscribers
*
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class ListenerProvider implements ListenerProviderInterface
{
private array $listeners = [];
private array $sorted = [];
/**
* {@inheritdoc}
*/
public function getListenersForEvent(object $event): iterable
{
return $this->getListenersForEventName($event::class);
}
/**
*/
public function add(string $eventName, callable|array $listener, int $priority = 0): void
{
$this->listeners[$eventName][$priority][] = $listener;
unset($this->sorted[$eventName]);
}
/**
*/
public function addSubscriber(EventSubscriberInterface $subscriber): void
{
foreach ($subscriber::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
// 'eventName' => 'methodName'
$this->add($eventName, [$subscriber, $params]);
} elseif (is_string($params[0])) {
// 'eventName' => ['methodName', $priority]
$this->add($eventName, [$subscriber, $params[0]], $params[1] ?? 0);
} else {
// 'eventName' => [['methodName1', $priority], ['methodName2']]
foreach ($params as $listener) {
$this->add($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0);
}
}
}
}
/**
*/
public function getListenersForEventName(string $eventName): iterable
{
if (!\array_key_exists($eventName, $this->listeners)) {
return [];
}
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
return $this->sorted[$eventName];
}
/**
*/
private function sortListeners(string $eventName): void
{
ksort($this->listeners[$eventName]);
$this->sorted[$eventName] = [];
foreach ($this->listeners[$eventName] as $listeners) {
foreach ($listeners as $listener) {
$this->sorted[$eventName][] = $listener;
}
}
}
}