-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListenerPriorityQueue.php
114 lines (100 loc) · 2.6 KB
/
ListenerPriorityQueue.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
/**
* Qubus\EventDispatcher
*
* @link https://github.com/QubusPHP/event-dispatcher
* @copyright 2020 Joshua Parker <joshua@joshuaparker.dev>
* @copyright 2018 Filip Štamcar (original author Tor Morten Jensen)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\EventDispatcher;
use IteratorAggregate;
use SplObjectStorage;
use SplPriorityQueue;
use Traversable;
class ListenerPriorityQueue implements IteratorAggregate
{
public function __construct(
protected SplObjectStorage $storage = new SplObjectStorage(),
protected SplPriorityQueue $queue = new SplPriorityQueue(),
) {
}
/**
* Insert a listener to the queue.
*
* @param EventListener $listener
* @param int $priority
*/
public function insert(EventListener $listener, int $priority): void
{
$this->storage->attach($listener, $priority);
$this->queue->insert($listener, $priority);
}
/**
* Removes an listener from the queue.
*/
public function detach(EventListener $listener): void
{
if ($this->storage->contains($listener)) {
$this->storage->detach($listener);
$this->refreshQueue();
}
}
/**
* Clears the queue.
*/
public function clear(): void
{
$this->storage = new SplObjectStorage();
$this->queue = new SplPriorityQueue();
}
/**
* Checks whether the queue contains the listener.
*
* @param EventListener $listener
* @return bool
*/
public function contains(EventListener $listener): bool
{
return $this->storage->contains($listener);
}
/**
* Gets all listeners.
*
* @return EventListener[]
*/
public function all(): array
{
$listeners = [];
foreach ($this->getIterator() as $listener) {
$listeners[] = $listener;
}
return $listeners;
}
/**
* Clones and returns a iterator.
*
* @return Traversable
*/
public function getIterator(): Traversable
{
$queue = clone $this->queue;
if (! $queue->isEmpty()) {
$queue->top();
}
return $queue;
}
/**
* Refreshes the status of the queue.
*/
protected function refreshQueue(): void
{
$this->storage->rewind();
$this->queue = new SplPriorityQueue();
foreach ($this->storage as $listener) {
$priority = $this->storage->getInfo();
$this->queue->insert($listener, $priority);
}
}
}