17
17
use function serialize ;
18
18
use function sprintf ;
19
19
use function unserialize ;
20
+ use function usort ;
20
21
21
22
/**
22
23
* Re-usable, serializable priority queue implementation
@@ -245,13 +246,12 @@ public function __unserialize(array $data): void
245
246
}
246
247
247
248
/**
248
- * Serialize to an array
249
- * By default, returns only the item data, and in the order registered (not
250
- * sorted). You may provide one of the EXTR_* flags as an argument, allowing
249
+ * Serialize to an array, ordered by priority
250
+ * By default, returns only the item data. You may provide one of the EXTR_* flags as an argument, allowing
251
251
* the ability to return priorities or both data and priority.
252
252
*
253
253
* @param self::EXTR_* $flag
254
- * @return array<array-key, mixed>
254
+ * @return list< mixed>
255
255
* @psalm-return ($flag is self::EXTR_BOTH
256
256
* ? list<array{data: TValue, priority: int}>
257
257
* : $flag is self::EXTR_PRIORITY
@@ -261,10 +261,19 @@ public function __unserialize(array $data): void
261
261
*/
262
262
public function toArray (int $ flag = self ::EXTR_DATA ): array
263
263
{
264
+ /**
265
+ * A manual sort is required because $item['priority'] as stored in the inner queue could be an array as
266
+ * opposed to an integer.
267
+ */
268
+ $ items = $ this ->items ;
269
+ usort ($ items , function (array $ a , array $ b ): int {
270
+ return $ b ['priority ' ] <=> $ a ['priority ' ];
271
+ });
272
+
264
273
return match ($ flag ) {
265
- self ::EXTR_BOTH => $ this -> items ,
266
- self ::EXTR_PRIORITY => array_map (static fn ($ item ): int => $ item ['priority ' ], $ this -> items ),
267
- default => array_map (static fn ($ item ): mixed => $ item ['data ' ], $ this -> items ),
274
+ self ::EXTR_BOTH => $ items ,
275
+ self ::EXTR_PRIORITY => array_map (static fn ($ item ): int => $ item ['priority ' ], $ items ),
276
+ default => array_map (static fn ($ item ): mixed => $ item ['data ' ], $ items ),
268
277
};
269
278
}
270
279
0 commit comments