TextResponseReader.php 2.1 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\IResponseReader;
  13. use Predis\Protocol\IResponseHandler;
  14. use Predis\Protocol\ProtocolException;
  15. use Predis\Network\IConnectionComposable;
  16. class TextResponseReader implements IResponseReader
  17. {
  18. private $_prefixHandlers;
  19. public function __construct()
  20. {
  21. $this->_prefixHandlers = $this->getDefaultHandlers();
  22. }
  23. private function getDefaultHandlers()
  24. {
  25. return array(
  26. TextProtocol::PREFIX_STATUS => new ResponseStatusHandler(),
  27. TextProtocol::PREFIX_ERROR => new ResponseErrorHandler(),
  28. TextProtocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
  29. TextProtocol::PREFIX_BULK => new ResponseBulkHandler(),
  30. TextProtocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  31. );
  32. }
  33. public function setHandler($prefix, IResponseHandler $handler)
  34. {
  35. $this->_prefixHandlers[$prefix] = $handler;
  36. }
  37. public function getHandler($prefix)
  38. {
  39. if (isset($this->_prefixHandlers[$prefix])) {
  40. return $this->_prefixHandlers[$prefix];
  41. }
  42. }
  43. public function read(IConnectionComposable $connection)
  44. {
  45. $header = $connection->readLine();
  46. if ($header === '') {
  47. $this->protocolError($connection, 'Unexpected empty header');
  48. }
  49. $prefix = $header[0];
  50. if (!isset($this->_prefixHandlers[$prefix])) {
  51. $this->protocolError($connection, "Unknown prefix '$prefix'");
  52. }
  53. $handler = $this->_prefixHandlers[$prefix];
  54. return $handler->handle($connection, substr($header, 1));
  55. }
  56. private function protocolError(IConnectionComposable $connection, $message)
  57. {
  58. Helpers::onCommunicationException(new ProtocolException($connection, $message));
  59. }
  60. }