MultiBulkResponseSimple.php 2.3 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\Iterator;
  11. use Predis\Connection\SingleConnectionInterface;
  12. /**
  13. * Streams a multibulk reply.
  14. *
  15. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. class MultiBulkResponseSimple extends MultiBulkResponse
  18. {
  19. private $connection;
  20. /**
  21. * @param SingleConnectionInterface $connection Connection to Redis.
  22. * @param int $size Number of elements of the multibulk reply.
  23. */
  24. public function __construct(SingleConnectionInterface $connection, $size)
  25. {
  26. $this->connection = $connection;
  27. $this->position = 0;
  28. $this->current = $size > 0 ? $this->getValue() : null;
  29. $this->replySize = $size;
  30. }
  31. /**
  32. * Handles the synchronization of the client with the Redis protocol
  33. * then PHP's garbage collector kicks in (e.g. then the iterator goes
  34. * out of the scope of a foreach).
  35. */
  36. public function __destruct()
  37. {
  38. $this->sync(true);
  39. }
  40. /**
  41. * Synchronizes the client with the queued elements that have not been
  42. * read from the connection by consuming the rest of the multibulk reply,
  43. * or simply by dropping the connection.
  44. *
  45. * @param Boolean $drop True to synchronize the client by dropping the connection.
  46. * False to synchronize the client by consuming the multibulk reply.
  47. */
  48. public function sync($drop = false)
  49. {
  50. if ($drop == true) {
  51. if ($this->valid()) {
  52. $this->position = $this->replySize;
  53. $this->connection->disconnect();
  54. }
  55. } else {
  56. while ($this->valid()) {
  57. $this->next();
  58. }
  59. }
  60. }
  61. /**
  62. * Reads the next item of the multibulk reply from the server.
  63. *
  64. * @return mixed
  65. */
  66. protected function getValue()
  67. {
  68. return $this->connection->read();
  69. }
  70. /**
  71. * Returns an iterator that reads the multi-bulk response as
  72. * list of tuples.
  73. *
  74. * @return MultiBulkResponseTuple
  75. */
  76. public function asTuple()
  77. {
  78. return new MultiBulkResponseTuple($this);
  79. }
  80. }