SplStack.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use ReturnTypeWillChange;
  5. use Serializable;
  6. use UnexpectedValueException;
  7. use function is_array;
  8. use function serialize;
  9. use function sprintf;
  10. use function unserialize;
  11. /**
  12. * Serializable version of SplStack
  13. *
  14. * @template TValue
  15. * @extends \SplStack<TValue>
  16. */
  17. class SplStack extends \SplStack implements Serializable
  18. {
  19. /**
  20. * Serialize to an array representing the stack
  21. *
  22. * @return list<TValue>
  23. */
  24. public function toArray()
  25. {
  26. $array = [];
  27. foreach ($this as $item) {
  28. $array[] = $item;
  29. }
  30. return $array;
  31. }
  32. /**
  33. * Serialize
  34. *
  35. * @return string
  36. */
  37. #[ReturnTypeWillChange]
  38. public function serialize()
  39. {
  40. return serialize($this->__serialize());
  41. }
  42. /**
  43. * Magic method used for serializing of an instance.
  44. *
  45. * @return list<TValue>
  46. */
  47. #[ReturnTypeWillChange]
  48. public function __serialize()
  49. {
  50. return $this->toArray();
  51. }
  52. /**
  53. * Unserialize
  54. *
  55. * @param string $data
  56. * @return void
  57. */
  58. #[ReturnTypeWillChange]
  59. public function unserialize($data)
  60. {
  61. $toUnserialize = unserialize($data);
  62. if (! is_array($toUnserialize)) {
  63. throw new UnexpectedValueException(sprintf(
  64. 'Cannot deserialize %s instance; corrupt serialization data',
  65. self::class
  66. ));
  67. }
  68. $this->__unserialize($toUnserialize);
  69. }
  70. /**
  71. * Magic method used to rebuild an instance.
  72. *
  73. * @param array<array-key, TValue> $data Data array.
  74. * @return void
  75. */
  76. #[ReturnTypeWillChange]
  77. public function __unserialize($data)
  78. {
  79. foreach ($data as $item) {
  80. $this->unshift($item);
  81. }
  82. }
  83. }