Iterator.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace RocketTheme\Toolbox\ArrayTraits;
  3. /**
  4. * Implements \Iterator interface.
  5. *
  6. * @package RocketTheme\Toolbox\ArrayTraits
  7. * @author RocketTheme
  8. * @license MIT
  9. *
  10. * @property array $items
  11. */
  12. trait Iterator
  13. {
  14. /**
  15. * Hack to make Iterator work together with unset().
  16. *
  17. * @var bool
  18. */
  19. private $iteratorUnset = false;
  20. /**
  21. * Returns the current element.
  22. *
  23. * @return mixed Can return any type.
  24. */
  25. public function current()
  26. {
  27. return current($this->items);
  28. }
  29. /**
  30. * Returns the key of the current element.
  31. *
  32. * @return mixed Returns scalar on success, or NULL on failure.
  33. */
  34. public function key()
  35. {
  36. return key($this->items);
  37. }
  38. /**
  39. * Moves the current position to the next element.
  40. *
  41. * @return void
  42. */
  43. public function next()
  44. {
  45. if ($this->iteratorUnset) {
  46. // If current item was unset, position is already in the next element (do nothing).
  47. $this->iteratorUnset = false;
  48. } else {
  49. next($this->items);
  50. }
  51. }
  52. /**
  53. * Rewinds back to the first element of the Iterator.
  54. *
  55. * @return void
  56. */
  57. public function rewind()
  58. {
  59. $this->iteratorUnset = false;
  60. reset($this->items);
  61. }
  62. /**
  63. * This method is called after Iterator::rewind() and Iterator::next() to check if the current position is valid.
  64. *
  65. * @return bool Returns TRUE on success or FALSE on failure.
  66. */
  67. public function valid()
  68. {
  69. return key($this->items) !== null;
  70. }
  71. }