MultiBulkResponseTuple.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. /**
  12. * Abstracts the access to a streamable list of tuples represented
  13. * as a multibulk reply that alternates keys and values.
  14. *
  15. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. class MultiBulkResponseTuple extends MultiBulkResponse implements \OuterIterator
  18. {
  19. private $iterator;
  20. /**
  21. * @param MultiBulkResponseSimple $iterator Multibulk reply iterator.
  22. */
  23. public function __construct(MultiBulkResponseSimple $iterator)
  24. {
  25. $this->checkPreconditions($iterator);
  26. $virtualSize = count($iterator) / 2;
  27. $this->iterator = $iterator;
  28. $this->position = $iterator->getPosition();
  29. $this->current = $virtualSize > 0 ? $this->getValue() : null;
  30. $this->replySize = $virtualSize;
  31. }
  32. /**
  33. * Checks for valid preconditions.
  34. *
  35. * @param MultiBulkResponseSimple $iterator Multibulk reply iterator.
  36. */
  37. protected function checkPreconditions(MultiBulkResponseSimple $iterator)
  38. {
  39. if ($iterator->getPosition() !== 0) {
  40. throw new \RuntimeException('Cannot initialize a tuple iterator with an already initiated iterator');
  41. }
  42. if (($size = count($iterator)) % 2 !== 0) {
  43. throw new \UnexpectedValueException("Invalid reply size for a tuple iterator [$size]");
  44. }
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function getInnerIterator()
  50. {
  51. return $this->iterator;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function __destruct()
  57. {
  58. $this->iterator->sync(true);
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. protected function getValue()
  64. {
  65. $k = $this->iterator->current();
  66. $this->iterator->next();
  67. $v = $this->iterator->current();
  68. $this->iterator->next();
  69. return array($k, $v);
  70. }
  71. }