TextResponseReader.php 1.8 KB

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