SplPriorityQueue.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Stdlib;
  12. use const PHP_INT_MAX;
  13. /**
  14. * Serializable version of SplPriorityQueue.
  15. *
  16. * Also, provides predictable heap order for datums added with the same priority
  17. * (i.e., they will be emitted in the same order they are enqueued).
  18. *
  19. * @template TValue
  20. * @template TPriority
  21. * @extends \SplPriorityQueue<TPriority, TValue>
  22. */
  23. class SplPriorityQueue extends \SplPriorityQueue
  24. {
  25. /**
  26. * Seed used to ensure queue order for items of the same priority.
  27. */
  28. protected int $serial = PHP_INT_MAX;
  29. /**
  30. * Insert a value with a given priority.
  31. *
  32. * Utilizes {@var to $serial} ensure that values of equal priority are
  33. * emitted in the same order in which they are inserted.
  34. *
  35. * @param TValue $value
  36. * @param TPriority $priority
  37. */
  38. public function insert(mixed $value, mixed $priority)
  39. {
  40. return parent::insert($value, [$priority, $this->serial--]);
  41. }
  42. /**
  43. * Serialize to an array.
  44. *
  45. * Array will be priority => data pairs
  46. *
  47. * @return list<TValue>
  48. */
  49. public function toArray(): array
  50. {
  51. $array = [];
  52. foreach (clone $this as $item) {
  53. $array[] = $item;
  54. }
  55. return $array;
  56. }
  57. }