TextResponseReader.php 1.8 KB

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