ComposableTextProtocol.php 2.3 KB

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