1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Arp\EventDispatcher\Listener; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @author Alex Patterson <[email protected]> |
9
|
|
|
* @package Arp\EventDispatcher\Listener |
10
|
|
|
*/ |
11
|
|
|
class ListenerCollection implements ListenerCollectionInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* The collection of listeners to iterate. |
15
|
|
|
* |
16
|
|
|
* @var \SplPriorityQueue|callable[] |
17
|
|
|
*/ |
18
|
|
|
private $listeners; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Internal count for the queue priority order. |
22
|
|
|
* |
23
|
|
|
* @var int |
24
|
|
|
*/ |
25
|
|
|
private $queueOrder = PHP_INT_MIN; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param iterable|callable[] $listeners |
29
|
|
|
*/ |
30
|
|
|
public function __construct(iterable $listeners = []) |
31
|
|
|
{ |
32
|
|
|
$this->listeners = new \SplPriorityQueue(); |
33
|
|
|
|
34
|
|
|
if (!empty($listeners)) { |
35
|
|
|
$this->addListeners($listeners); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Add a collection of listeners to the collection. |
41
|
|
|
* |
42
|
|
|
* @param callable[] $listeners The collection of event listeners to add. |
43
|
|
|
* @param int $priority Optional priority for the listener. |
44
|
|
|
*/ |
45
|
|
|
public function addListeners(iterable $listeners, int $priority = 1): void |
46
|
|
|
{ |
47
|
|
|
foreach ($listeners as $listener) { |
48
|
|
|
$this->addListener($listener, $priority); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Add a single listener to the collection. |
54
|
|
|
* |
55
|
|
|
* @param callable $listener The listener that should be attached. |
56
|
|
|
* @param int $priority Optional priority for the listener. |
57
|
|
|
*/ |
58
|
|
|
public function addListener(callable $listener, int $priority = 1): void |
59
|
|
|
{ |
60
|
|
|
$this->listeners->insert($listener, [$priority, $this->queueOrder++]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Return the listener iterator |
65
|
|
|
* |
66
|
|
|
* @return \Traversable |
67
|
|
|
*/ |
68
|
|
|
public function getIterator(): \Traversable |
69
|
|
|
{ |
70
|
|
|
$clone = clone $this->listeners; |
71
|
|
|
|
72
|
|
|
$clone->rewind(); |
73
|
|
|
|
74
|
|
|
return $clone; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Return the number of records in the collection. |
79
|
|
|
* |
80
|
|
|
* @return int |
81
|
|
|
*/ |
82
|
|
|
public function count(): int |
83
|
|
|
{ |
84
|
|
|
return $this->listeners->count(); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|