MultiBulkResponseSimple.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. }