ComposableTextProtocol.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Predis\Protocols\Text;
  3. use Predis\Commands\ICommand;
  4. use Predis\Protocols\IResponseReader;
  5. use Predis\Protocols\ICommandSerializer;
  6. use Predis\Protocols\IComposableProtocolProcessor;
  7. use Predis\Network\IConnectionComposable;
  8. class ComposableTextProtocol implements IComposableProtocolProcessor {
  9. private $_serializer, $_reader;
  10. public function __construct(Array $options = array()) {
  11. $this->setSerializer(new TextCommandSerializer());
  12. $this->setReader(new TextResponseReader());
  13. if (count($options) > 0) {
  14. $this->initializeOptions($options);
  15. }
  16. }
  17. private function initializeOptions(Array $options) {
  18. foreach ($options as $k => $v) {
  19. $this->setOption($k, $v);
  20. }
  21. }
  22. public function setOption($option, $value) {
  23. switch ($option) {
  24. case 'iterable_multibulk':
  25. $handler = $value ? new ResponseMultiBulkStreamHandler() : new ResponseMultiBulkHandler();
  26. $this->_reader->setHandler(TextProtocol::PREFIX_MULTI_BULK, $handler);
  27. break;
  28. case 'throw_errors':
  29. $handler = $value ? new ResponseErrorHandler() : new ResponseErrorSilentHandler();
  30. $this->_reader->setHandler(TextProtocol::PREFIX_ERROR, $handler);
  31. break;
  32. default:
  33. throw new \InvalidArgumentException(
  34. "The option $option is not supported by the current protocol"
  35. );
  36. }
  37. }
  38. public function serialize(ICommand $command) {
  39. return $this->_serializer->serialize($command);
  40. }
  41. public function write(IConnectionComposable $connection, ICommand $command) {
  42. $connection->writeBytes($this->_serializer->serialize($command));
  43. }
  44. public function read(IConnectionComposable $connection) {
  45. return $this->_reader->read($connection);
  46. }
  47. public function setSerializer(ICommandSerializer $serializer) {
  48. $this->_serializer = $serializer;
  49. }
  50. public function getSerializer() {
  51. return $this->_serializer;
  52. }
  53. public function setReader(IResponseReader $reader) {
  54. $this->_reader = $reader;
  55. }
  56. public function getReader() {
  57. return $this->_reader;
  58. }
  59. }