MultiBulkResponse.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. * @author Daniele Alessandri <suppakilla@gmail.com>
  20. */
  21. class MultiBulkResponse implements ResponseHandlerInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function handle(CompositeConnectionInterface $connection, $payload)
  27. {
  28. $length = (int) $payload;
  29. if ("$length" !== $payload) {
  30. CommunicationException::handle(new ProtocolException(
  31. $connection, "Cannot parse '$payload' as a valid length of a multi-bulk response."
  32. ));
  33. }
  34. if ($length === -1) {
  35. return null;
  36. }
  37. $list = array();
  38. if ($length > 0) {
  39. $handlersCache = array();
  40. $reader = $connection->getProtocol()->getResponseReader();
  41. for ($i = 0; $i < $length; $i++) {
  42. $header = $connection->readLine();
  43. $prefix = $header[0];
  44. if (isset($handlersCache[$prefix])) {
  45. $handler = $handlersCache[$prefix];
  46. } else {
  47. $handler = $reader->getHandler($prefix);
  48. $handlersCache[$prefix] = $handler;
  49. }
  50. $list[$i] = $handler->handle($connection, substr($header, 1));
  51. }
  52. }
  53. return $list;
  54. }
  55. }