SplPriorityQueue.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 ReturnTypeWillChange;
  13. use const PHP_INT_MAX;
  14. /**
  15. * Serializable version of SplPriorityQueue.
  16. *
  17. * Also, provides predictable heap order for datums added with the same priority
  18. * (i.e., they will be emitted in the same order they are enqueued).
  19. *
  20. * @template TValue
  21. * @template TPriority
  22. * @extends \SplPriorityQueue<TPriority, TValue>
  23. */
  24. class SplPriorityQueue extends \SplPriorityQueue
  25. {
  26. /**
  27. * Seed used to ensure queue order for items of the same priority.
  28. */
  29. protected int $serial = PHP_INT_MAX;
  30. /**
  31. * Insert a value with a given priority.
  32. *
  33. * Utilizes {@var to $serial} ensure that values of equal priority are
  34. * emitted in the same order in which they are inserted.
  35. *
  36. * @param TValue $value
  37. * @param TPriority $priority
  38. */
  39. #[ReturnTypeWillChange]
  40. public function insert(mixed $value, mixed $priority): bool
  41. {
  42. return parent::insert($value, [$priority, $this->serial--]);
  43. }
  44. /**
  45. * Serialize to an array.
  46. *
  47. * Array will be priority => data pairs
  48. *
  49. * @return list<TValue>
  50. */
  51. public function toArray(): array
  52. {
  53. $array = [];
  54. foreach (clone $this as $item) {
  55. $array[] = $item;
  56. }
  57. return $array;
  58. }
  59. }