ResponseMultiBulkHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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;
  11. use Predis\Helpers;
  12. use Predis\Connection\ComposableConnectionInterface;
  13. use Predis\Protocol\ProtocolException;
  14. use Predis\Protocol\ResponseHandlerInterface;
  15. /**
  16. * Implements a response handler for multi-bulk replies using the standard
  17. * wire protocol defined by Redis.
  18. *
  19. * @link http://redis.io/topics/protocol
  20. * @author Daniele Alessandri <suppakilla@gmail.com>
  21. */
  22. class ResponseMultiBulkHandler implements ResponseHandlerInterface
  23. {
  24. /**
  25. * Handles a multi-bulk reply returned by Redis.
  26. *
  27. * @param ComposableConnectionInterface $connection Connection to Redis.
  28. * @param string $lengthString Number of items in the multi-bulk reply.
  29. * @return array
  30. */
  31. public function handle(ComposableConnectionInterface $connection, $lengthString)
  32. {
  33. $length = (int) $lengthString;
  34. if ("$length" !== $lengthString) {
  35. Helpers::onCommunicationException(new ProtocolException(
  36. $connection, "Cannot parse '$lengthString' as multi-bulk length"
  37. ));
  38. }
  39. if ($length === -1) {
  40. return null;
  41. }
  42. $list = array();
  43. if ($length > 0) {
  44. $handlersCache = array();
  45. $reader = $connection->getProtocol()->getReader();
  46. for ($i = 0; $i < $length; $i++) {
  47. $header = $connection->readLine();
  48. $prefix = $header[0];
  49. if (isset($handlersCache[$prefix])) {
  50. $handler = $handlersCache[$prefix];
  51. } else {
  52. $handler = $reader->getHandler($prefix);
  53. $handlersCache[$prefix] = $handler;
  54. }
  55. $list[$i] = $handler->handle($connection, substr($header, 1));
  56. }
  57. }
  58. return $list;
  59. }
  60. }