SplPriorityQueue.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Stdlib;
  10. use Serializable;
  11. /**
  12. * Serializable version of SplPriorityQueue
  13. *
  14. * Also, provides predictable heap order for datums added with the same priority
  15. * (i.e., they will be emitted in the same order they are enqueued).
  16. */
  17. class SplPriorityQueue extends \SplPriorityQueue implements Serializable
  18. {
  19. /**
  20. * @var int Seed used to ensure queue order for items of the same priority
  21. */
  22. protected $serial = PHP_INT_MAX;
  23. /**
  24. * Insert a value with a given priority
  25. *
  26. * Utilizes {@var $serial} to ensure that values of equal priority are
  27. * emitted in the same order in which they are inserted.
  28. *
  29. * @param mixed $datum
  30. * @param mixed $priority
  31. * @return void
  32. */
  33. public function insert($datum, $priority)
  34. {
  35. if (!is_array($priority)) {
  36. $priority = array($priority, $this->serial--);
  37. }
  38. parent::insert($datum, $priority);
  39. }
  40. /**
  41. * Serialize to an array
  42. *
  43. * Array will be priority => data pairs
  44. *
  45. * @return array
  46. */
  47. public function toArray()
  48. {
  49. $array = array();
  50. foreach (clone $this as $item) {
  51. $array[] = $item;
  52. }
  53. return $array;
  54. }
  55. /**
  56. * Serialize
  57. *
  58. * @return string
  59. */
  60. public function serialize()
  61. {
  62. $clone = clone $this;
  63. $clone->setExtractFlags(self::EXTR_BOTH);
  64. $data = array();
  65. foreach ($clone as $item) {
  66. $data[] = $item;
  67. }
  68. return serialize($data);
  69. }
  70. /**
  71. * Deserialize
  72. *
  73. * @param string $data
  74. * @return void
  75. */
  76. public function unserialize($data)
  77. {
  78. foreach (unserialize($data) as $item) {
  79. $this->insert($item['data'], $item['priority']);
  80. }
  81. }
  82. }