MultiBulkIterator.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Response\Iterator;
  11. use Predis\Response\ResponseInterface;
  12. /**
  13. * Iterator that abstracts the access to multibulk responses allowing them to be
  14. * consumed in a streamable fashion without keeping the whole payload in memory.
  15. *
  16. * This iterator does not support rewinding which means that the iteration, once
  17. * consumed, cannot be restarted.
  18. *
  19. * Always make sure that the whole iteration is consumed (or dropped) to prevent
  20. * protocol desynchronization issues.
  21. *
  22. * @author Daniele Alessandri <suppakilla@gmail.com>
  23. */
  24. abstract class MultiBulkIterator implements \Iterator, \Countable, ResponseInterface
  25. {
  26. protected $current;
  27. protected $position;
  28. protected $size;
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function rewind()
  33. {
  34. // NOOP
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function current()
  40. {
  41. return $this->current;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function key()
  47. {
  48. return $this->position;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function next()
  54. {
  55. if (++$this->position < $this->size) {
  56. $this->current = $this->getValue();
  57. }
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function valid()
  63. {
  64. return $this->position < $this->size;
  65. }
  66. /**
  67. * Returns the number of items comprising the whole multibulk response.
  68. *
  69. * This method should be used instead of iterator_count() to get the size of
  70. * the current multibulk response since the former consumes the iteration to
  71. * count the number of elements, but our iterators do not support rewinding.
  72. *
  73. * @return int
  74. */
  75. public function count()
  76. {
  77. return $this->size;
  78. }
  79. /**
  80. * Returns the current position of the iterator.
  81. *
  82. * @return int
  83. */
  84. public function getPosition()
  85. {
  86. return $this->position;
  87. }
  88. /**
  89. * {@inheritdoc}
  90. */
  91. abstract protected function getValue();
  92. }