TextResponseReader.php 1.7 KB

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