forked from thephpleague/event
/
PrioritizedListenersForEvent.php
47 lines (39 loc) · 1.16 KB
/
PrioritizedListenersForEvent.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
<?php
declare(strict_types=1);
namespace League\Event;
use const SORT_NUMERIC;
/**
* @internal
*/
class PrioritizedListenersForEvent
{
/** @var array<int, array<int,callable>> */
private $listeners = [];
/** @var array<int,callable>|null */
private $sortedListeners;
public function addListener(callable $listener, int $priority): void
{
$this->sortedListeners = null;
$this->listeners[$priority][] = $listener;
}
public function getListeners(): iterable
{
return $this->sortedListeners ?? $this->sortListeners();
}
private function sortListeners(): array
{
$filter = static function ($listener): bool {
return $listener instanceof OneTimeListener === false;
};
krsort($this->listeners, SORT_NUMERIC);
$listeners = [];
foreach ($this->listeners as $priority => $group) {
foreach ($group as $listener) {
$listeners[] = $listener;
}
$this->listeners[$priority] = array_filter($group, $filter);
}
$this->sortedListeners = array_filter($listeners, $filter);
return $listeners;
}
}