MultiBulkTuple.php 2.1 KB

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