ComposableTextProtocol.php 2.5 KB

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