MultiBulkResponse.php 2.3 KB

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