ResponseMultiBulkHandler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\Protocol\IResponseHandler;
  13. use Predis\Protocol\ProtocolException;
  14. use Predis\Network\IConnectionComposable;
  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 IResponseHandler
  23. {
  24. /**
  25. * Handles a multi-bulk reply returned by Redis.
  26. *
  27. * @param IConnectionComposable $connection Connection to Redis.
  28. * @param string $lengthString Number of items in the multi-bulk reply.
  29. * @return array
  30. */
  31. public function handle(IConnectionComposable $connection, $lengthString)
  32. {
  33. $length = (int) $lengthString;
  34. if ($length != $lengthString) {
  35. Helpers::onCommunicationException(new ProtocolException(
  36. $connection, "Cannot parse '$length' as data 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. }
  52. else {
  53. $handler = $reader->getHandler($prefix);
  54. $handlersCache[$prefix] = $handler;
  55. }
  56. $list[$i] = $handler->handle($connection, substr($header, 1));
  57. }
  58. }
  59. return $list;
  60. }
  61. }