MultiBulkTuple.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 InvalidArgumentException;
  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 InvalidArgumentException(
  46. 'Cannot initialize a tuple iterator using an already initiated iterator.'
  47. );
  48. }
  49. if (($size = count($iterator)) % 2 !== 0) {
  50. throw new UnexpectedValueException("Invalid response size for a tuple iterator.");
  51. }
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getInnerIterator()
  57. {
  58. return $this->iterator;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function __destruct()
  64. {
  65. $this->iterator->drop(true);
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. protected function getValue()
  71. {
  72. $k = $this->iterator->current();
  73. $this->iterator->next();
  74. $v = $this->iterator->current();
  75. $this->iterator->next();
  76. return array($k, $v);
  77. }
  78. }