iterator_041.phpt 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. --TEST--
  2. SPL: iterator_to_array() and exceptions
  3. --FILE--
  4. <?php
  5. class MyArrayIterator extends ArrayIterator
  6. {
  7. static protected $fail = 0;
  8. public $state;
  9. static function fail($state, $method)
  10. {
  11. if (self::$fail == $state)
  12. {
  13. throw new Exception("State $state: $method()");
  14. }
  15. }
  16. function __construct()
  17. {
  18. $this->state = MyArrayIterator::$fail;
  19. self::fail(0, __FUNCTION__);
  20. parent::__construct(array(1, 2));
  21. self::fail(1, __FUNCTION__);
  22. }
  23. function rewind(): void
  24. {
  25. self::fail(2, __FUNCTION__);
  26. parent::rewind();
  27. }
  28. function valid(): bool
  29. {
  30. self::fail(3, __FUNCTION__);
  31. return parent::valid();
  32. }
  33. function current(): mixed
  34. {
  35. self::fail(4, __FUNCTION__);
  36. return parent::current();
  37. }
  38. function key(): string|int|null
  39. {
  40. self::fail(5, __FUNCTION__);
  41. return parent::key();
  42. }
  43. function next(): void
  44. {
  45. self::fail(6, __FUNCTION__);
  46. parent::next();
  47. }
  48. function __destruct()
  49. {
  50. // self::fail(7, __FUNCTION__);
  51. }
  52. static function test($func, $skip = null)
  53. {
  54. echo "===$func===\n";
  55. self::$fail = 0;
  56. while(self::$fail < 10)
  57. {
  58. try
  59. {
  60. var_dump($func(new MyArrayIterator()));
  61. break;
  62. }
  63. catch (Exception $e)
  64. {
  65. echo $e->getMessage() . "\n";
  66. }
  67. if (isset($skip[self::$fail]))
  68. {
  69. self::$fail = $skip[self::$fail];
  70. }
  71. else
  72. {
  73. self::$fail++;
  74. }
  75. }
  76. }
  77. }
  78. MyArrayIterator::test('iterator_to_array');
  79. MyArrayIterator::test('iterator_count', array(3 => 6));
  80. ?>
  81. --EXPECT--
  82. ===iterator_to_array===
  83. State 0: __construct()
  84. State 1: __construct()
  85. State 2: rewind()
  86. State 3: valid()
  87. State 4: current()
  88. State 5: key()
  89. State 6: next()
  90. array(2) {
  91. [0]=>
  92. int(1)
  93. [1]=>
  94. int(2)
  95. }
  96. ===iterator_count===
  97. State 0: __construct()
  98. State 1: __construct()
  99. State 2: rewind()
  100. State 3: valid()
  101. State 6: next()
  102. int(2)