MultiBulkTuple.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 OuterIterator;
  12. use RuntimeException;
  13. use UnexpectedValueException;
  14. /**
  15. * Outer iterator consuming streamable multibulk responses by yielding tuples of
  16. * keys and values.
  17. *
  18. * This wrapper is useful for responses to commands such as `HGETALL` that can
  19. * be iterater as $key => $value pairs.
  20. *
  21. * @author Daniele Alessandri <suppakilla@gmail.com>
  22. */
  23. class MultiBulkTuple extends MultiBulk implements OuterIterator
  24. {
  25. private $iterator;
  26. /**
  27. * @param MultiBulk $iterator Inner multibulk response iterator.
  28. */
  29. public function __construct(MultiBulk $iterator)
  30. {
  31. $this->checkPreconditions($iterator);
  32. $this->size = count($iterator) / 2;
  33. $this->iterator = $iterator;
  34. $this->position = $iterator->getPosition();
  35. $this->current = $this->size > 0 ? $this->getValue() : null;
  36. }
  37. /**
  38. * Checks for valid preconditions.
  39. *
  40. * @param MultiBulk $iterator Inner multibulk response iterator.
  41. */
  42. protected function checkPreconditions(MultiBulk $iterator)
  43. {
  44. if ($iterator->getPosition() !== 0) {
  45. throw new RuntimeException(
  46. 'Cannot initialize a tuple iterator with an already initiated iterator'
  47. );
  48. }
  49. if (($size = count($iterator)) % 2 !== 0) {
  50. throw new UnexpectedValueException(
  51. "Invalid response size for a tuple iterator [$size]"
  52. );
  53. }
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function getInnerIterator()
  59. {
  60. return $this->iterator;
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function __destruct()
  66. {
  67. $this->iterator->drop(true);
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected function getValue()
  73. {
  74. $k = $this->iterator->current();
  75. $this->iterator->next();
  76. $v = $this->iterator->current();
  77. $this->iterator->next();
  78. return array($k, $v);
  79. }
  80. }