MultiBulk.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\SingleConnectionInterface;
  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 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->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
  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->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 reply from the server.
  62. *
  63. * @return mixed
  64. */
  65. protected function getValue()
  66. {
  67. return $this->connection->read();
  68. }
  69. /**
  70. * Returns an iterator that reads the multi-bulk response as
  71. * list of tuples.
  72. *
  73. * @return MultiBulkTuple
  74. */
  75. public function asTuple()
  76. {
  77. return new MultiBulkTuple($this);
  78. }
  79. }