ComposableStreamConnection.php 2.4 KB

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