MultiBulkTuple.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /**
  12. * Outer iterator consuming streamable multibulk responses by yielding tuples of
  13. * keys and values.
  14. *
  15. * This wrapper is useful for responses to commands such as `HGETALL` that can
  16. * be iterater as $key => $value pairs.
  17. *
  18. * @author Daniele Alessandri <suppakilla@gmail.com>
  19. */
  20. class MultiBulkTuple extends MultiBulk implements \OuterIterator
  21. {
  22. private $iterator;
  23. /**
  24. * @param MultiBulk $iterator Inner multibulk response iterator.
  25. */
  26. public function __construct(MultiBulk $iterator)
  27. {
  28. $this->checkPreconditions($iterator);
  29. $this->size = count($iterator) / 2;
  30. $this->iterator = $iterator;
  31. $this->position = $iterator->getPosition();
  32. $this->current = $this->size > 0 ? $this->getValue() : null;
  33. }
  34. /**
  35. * Checks for valid preconditions.
  36. *
  37. * @param MultiBulk $iterator Inner multibulk response iterator.
  38. *
  39. * @throws \InvalidArgumentException
  40. * @throws \UnexpectedValueException
  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. }