ComposableStreamConnection.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\IConnectionParameters;
  4. use Predis\Commands\ICommand;
  5. use Predis\Protocol\IProtocolProcessor;
  6. use Predis\Protocol\Text\TextProtocol;
  7. class ComposableStreamConnection extends StreamConnection implements IConnectionComposable
  8. {
  9. private $_protocol;
  10. public function __construct(IConnectionParameters $parameters, IProtocolProcessor $protocol = null)
  11. {
  12. $this->setProtocol($protocol ?: new TextProtocol());
  13. parent::__construct($parameters);
  14. }
  15. protected function initializeProtocol(IConnectionParameters $parameters)
  16. {
  17. $this->_protocol->setOption('throw_errors', $parameters->throw_errors);
  18. $this->_protocol->setOption('iterable_multibulk', $parameters->iterable_multibulk);
  19. }
  20. public function setProtocol(IProtocolProcessor $protocol)
  21. {
  22. if ($protocol === null) {
  23. throw new \InvalidArgumentException("The protocol instance cannot be a null value");
  24. }
  25. $this->_protocol = $protocol;
  26. }
  27. public function getProtocol()
  28. {
  29. return $this->_protocol;
  30. }
  31. public function writeBytes($buffer)
  32. {
  33. parent::writeBytes($buffer);
  34. }
  35. public function readBytes($length)
  36. {
  37. if ($length <= 0) {
  38. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  39. }
  40. $value = '';
  41. $socket = $this->getResource();
  42. do {
  43. $chunk = fread($socket, $length);
  44. if ($chunk === false || $chunk === '') {
  45. $this->onConnectionError('Error while reading bytes from the server');
  46. }
  47. $value .= $chunk;
  48. }
  49. while (($length -= strlen($chunk)) > 0);
  50. return $value;
  51. }
  52. public function readLine()
  53. {
  54. $value = '';
  55. $socket = $this->getResource();
  56. do {
  57. $chunk = fgets($socket);
  58. if ($chunk === false || $chunk === '') {
  59. $this->onConnectionError('Error while reading line from the server');
  60. }
  61. $value .= $chunk;
  62. }
  63. while (substr($value, -2) !== "\r\n");
  64. return substr($value, 0, -2);
  65. }
  66. public function writeCommand(ICommand $command)
  67. {
  68. $this->_protocol->write($this, $command);
  69. }
  70. public function read()
  71. {
  72. return $this->_protocol->read($this);
  73. }
  74. }