ComposableStreamConnection.php 2.3 KB

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