MultiBulkResponseSimple.php 2.1 KB

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