MultiBulkResponse.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\Protocol\Text\Handler;
  11. use Predis\CommunicationException;
  12. use Predis\Connection\CompositeConnectionInterface;
  13. use Predis\Protocol\ProtocolException;
  14. /**
  15. * Handler for the multibulk response type in the standard Redis wire protocol.
  16. * It returns multibulk responses as PHP arrays.
  17. *
  18. * @link http://redis.io/topics/protocol
  19. *
  20. * @author Daniele Alessandri <suppakilla@gmail.com>
  21. */
  22. class MultiBulkResponse implements ResponseHandlerInterface
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function handle(CompositeConnectionInterface $connection, $payload)
  28. {
  29. $length = (int) $payload;
  30. if ("$length" !== $payload) {
  31. CommunicationException::handle(new ProtocolException(
  32. $connection, "Cannot parse '$payload' as a valid length of a multi-bulk response."
  33. ));
  34. }
  35. if ($length === -1) {
  36. return;
  37. }
  38. $list = array();
  39. if ($length > 0) {
  40. $handlersCache = array();
  41. $reader = $connection->getProtocol()->getResponseReader();
  42. for ($i = 0; $i < $length; ++$i) {
  43. $header = $connection->readLine();
  44. $prefix = $header[0];
  45. if (isset($handlersCache[$prefix])) {
  46. $handler = $handlersCache[$prefix];
  47. } else {
  48. $handler = $reader->getHandler($prefix);
  49. $handlersCache[$prefix] = $handler;
  50. }
  51. $list[$i] = $handler->handle($connection, substr($header, 1));
  52. }
  53. }
  54. return $list;
  55. }
  56. }