-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPriorityQueue.php
407 lines (361 loc) · 10.4 KB
/
PriorityQueue.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
declare(strict_types=1);
/*
* CoreShop
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - CoreShop Commercial License (CCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) CoreShop GmbH (https://www.coreshop.org)
* @license https://www.coreshop.org/license GPLv3 and CCL
*
*/
namespace CoreShop\Component\Pimcore;
use function array_map;
use function count;
use Countable;
use function is_array;
use IteratorAggregate;
use ReturnTypeWillChange;
use Serializable;
use function serialize;
use function sprintf;
use UnexpectedValueException;
use function unserialize;
/**
* Re-usable, serializable priority queue implementation
*
* SplPriorityQueue acts as a heap; on iteration, each item is removed from the
* queue. If you wish to re-use such a queue, you need to clone it first. This
* makes for some interesting issues if you wish to delete items from the queue,
* or, as already stated, iterate over it multiple times.
*
* This class aggregates items for the queue itself, but also composes an
* "inner" iterator in the form of an SplPriorityQueue object for performing
* the actual iteration.
*
* @template TValue
* @template TPriority of int
*
* @implements IteratorAggregate<array-key, TValue>
*/
class PriorityQueue implements Countable, IteratorAggregate, Serializable
{
public const EXTR_DATA = 0x00000001;
public const EXTR_PRIORITY = 0x00000002;
public const EXTR_BOTH = 0x00000003;
/**
* Inner queue class to use for iteration
*
* @var class-string<\SplPriorityQueue>
*/
protected $queueClass = SplPriorityQueue::class;
/**
* Actual items aggregated in the priority queue. Each item is an array
* with keys "data" and "priority".
*
* @var list<array{data: TValue, priority: TPriority}>
*/
protected $items = [];
/**
* Inner queue object
*
* @var \SplPriorityQueue<TPriority, TValue>|null
*/
protected $queue;
/**
* Insert an item into the queue
*
* Priority defaults to 1 (low priority) if none provided.
*
* @param TValue $data
* @param TPriority $priority
*
* @return $this
*/
public function insert($data, $priority = 1)
{
/** @psalm-var TPriority $priority */
$priority = (int) $priority;
$this->items[] = [
'data' => $data,
'priority' => $priority,
];
$this->getQueue()->insert($data, $priority);
return $this;
}
/**
* Remove an item from the queue
*
* This is different than {@link extract()}; its purpose is to dequeue an
* item.
*
* This operation is potentially expensive, as it requires
* re-initialization and re-population of the inner queue.
*
* Note: this removes the first item matching the provided item found. If
* the same item has been added multiple times, it will not remove other
* instances.
*
* @return bool False if the item was not found, true otherwise.
*/
public function remove(mixed $datum)
{
$found = false;
$key = null;
foreach ($this->items as $key => $item) {
if ($item['data'] === $datum) {
$found = true;
break;
}
}
if ($found && $key !== null) {
unset($this->items[$key]);
$this->queue = null;
if (!$this->isEmpty()) {
$queue = $this->getQueue();
foreach ($this->items as $item) {
$queue->insert($item['data'], $item['priority']);
}
}
return true;
}
return false;
}
/**
* Is the queue empty?
*
* @return bool
*/
public function isEmpty()
{
return 0 === $this->count();
}
/**
* How many items are in the queue?
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->items);
}
/**
* Peek at the top node in the queue, based on priority.
*
* @return TValue
*/
public function top()
{
$queue = clone $this->getQueue();
return $queue->top();
}
/**
* Extract a node from the inner queue and sift up
*
* @return TValue
*/
public function extract()
{
$value = $this->getQueue()->extract();
$keyToRemove = null;
$highestPriority = null;
foreach ($this->items as $key => $item) {
if ($item['data'] !== $value) {
continue;
}
if (null === $highestPriority) {
$highestPriority = $item['priority'];
$keyToRemove = $key;
continue;
}
if ($highestPriority >= $item['priority']) {
continue;
}
$highestPriority = $item['priority'];
$keyToRemove = $key;
}
if ($keyToRemove !== null) {
unset($this->items[$keyToRemove]);
}
return $value;
}
/**
* Retrieve the inner iterator
*
* SplPriorityQueue acts as a heap, which typically implies that as items
* are iterated, they are also removed. This does not work for situations
* where the queue may be iterated multiple times. As such, this class
* aggregates the values, and also injects an SplPriorityQueue. This method
* retrieves the inner queue object, and clones it for purposes of
* iteration.
*
* @return \SplPriorityQueue<TPriority, TValue>
*/
#[ReturnTypeWillChange]
public function getIterator()
{
$queue = $this->getQueue();
return clone $queue;
}
/**
* Serialize the data structure
*
* @return string
*/
public function serialize()
{
return serialize($this->__serialize());
}
/**
* Magic method used for serializing of an instance.
*
* @return list<array{data: TValue, priority: TPriority}>
*/
public function __serialize()
{
return $this->items;
}
/**
* Unserialize a string into a PriorityQueue object
*
* Serialization format is compatible with {@link SplPriorityQueue}
*
* @param string $data
*/
public function unserialize($data)
{
$toUnserialize = unserialize($data);
if (!is_array($toUnserialize)) {
throw new UnexpectedValueException(sprintf(
'Cannot deserialize %s instance; corrupt serialization data',
self::class,
));
}
/** @psalm-var list<array{data: TValue, priority: TPriority}> $toUnserialize */
$this->__unserialize($toUnserialize);
}
/**
* Magic method used to rebuild an instance.
*
* @param list<array{data: TValue, priority: TPriority}> $data Data array.
*/
public function __unserialize($data)
{
foreach ($data as $item) {
$this->insert($item['data'], $item['priority']);
}
}
/**
* Serialize to an array
* By default, returns only the item data, and in the order registered (not
* sorted). You may provide one of the EXTR_* flags as an argument, allowing
* the ability to return priorities or both data and priority.
*
* @param int $flag
*
* @return array<array-key, mixed>
*
* @psalm-return ($flag is self::EXTR_BOTH
* ? list<array{data: TValue, priority: TPriority}>
* : $flag is self::EXTR_PRIORITY
* ? list<TPriority>
* : list<TValue>
* )
*/
public function toArray($flag = self::EXTR_DATA)
{
return match ($flag) {
self::EXTR_BOTH => $this->items,
self::EXTR_PRIORITY => array_map(static fn ($item): int => $item['priority'], $this->items),
default => array_map(static fn ($item): mixed => $item['data'], $this->items),
};
}
/**
* Specify the internal queue class
*
* Please see {@link getIterator()} for details on the necessity of an
* internal queue class. The class provided should extend SplPriorityQueue.
*
* @param class-string<\SplPriorityQueue> $class
*
* @return $this
*/
public function setInternalQueueClass($class)
{
/** @psalm-suppress RedundantCastGivenDocblockType */
$this->queueClass = (string) $class;
return $this;
}
/**
* Does the queue contain the given datum?
*
* @param TValue $datum
*
* @return bool
*/
public function contains($datum)
{
foreach ($this->items as $item) {
if ($item['data'] === $datum) {
return true;
}
}
return false;
}
/**
* Does the queue have an item with the given priority?
*
* @param TPriority $priority
*
* @return bool
*/
public function hasPriority($priority)
{
foreach ($this->items as $item) {
if ($item['priority'] === $priority) {
return true;
}
}
return false;
}
/**
* Get the inner priority queue instance
*
* @throws \Exception
*
* @return \SplPriorityQueue<TPriority, TValue>
*
* @psalm-assert !null $this->queue
*/
protected function getQueue()
{
if (null === $this->queue) {
/** @psalm-suppress UnsafeInstantiation */
$queue = new $this->queueClass();
/** @psalm-var \SplPriorityQueue<TPriority, TValue> $queue */
$this->queue = $queue;
/** @psalm-suppress DocblockTypeContradiction */
if (!$this->queue instanceof \SplPriorityQueue) {
throw new \Exception(sprintf(
'PriorityQueue expects an internal queue of type SplPriorityQueue; received "%s"',
$queue::class,
));
}
}
return $this->queue;
}
/**
* Add support for deep cloning
*/
public function __clone()
{
if (null !== $this->queue) {
$this->queue = clone $this->queue;
}
}
}