MultiBulk.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. use Predis\Connection\NodeConnectionInterface;
  12. /**
  13. * Streamable multibulk response.
  14. *
  15. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. class MultiBulk extends MultiBulkIterator
  18. {
  19. private $connection;
  20. /**
  21. * @param NodeConnectionInterface $connection Connection to Redis.
  22. * @param int $size Number of elements of the multibulk response.
  23. */
  24. public function __construct(NodeConnectionInterface $connection, $size)
  25. {
  26. $this->connection = $connection;
  27. $this->size = $size;
  28. $this->position = 0;
  29. $this->current = $size > 0 ? $this->getValue() : null;
  30. }
  31. /**
  32. * Handles the synchronization of the client with the Redis protocol when
  33. * the garbage collector kicks in (e.g. when the iterator goes out of the
  34. * scope of a foreach or it is unset).
  35. */
  36. public function __destruct()
  37. {
  38. $this->drop(true);
  39. }
  40. /**
  41. * Drop queued elements that have not been read from the connection either
  42. * by consuming the rest of the multibulk response or quickly by closing the
  43. * underlying connection.
  44. *
  45. * @param bool $disconnect Consume the iterator or drop the connection.
  46. */
  47. public function drop($disconnect = false)
  48. {
  49. if ($disconnect) {
  50. if ($this->valid()) {
  51. $this->position = $this->size;
  52. $this->connection->disconnect();
  53. }
  54. } else {
  55. while ($this->valid()) {
  56. $this->next();
  57. }
  58. }
  59. }
  60. /**
  61. * Reads the next item of the multibulk response from the connection.
  62. *
  63. * @return mixed
  64. */
  65. protected function getValue()
  66. {
  67. return $this->connection->read();
  68. }
  69. }