ComposableStreamConnection.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\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($value) {
  28. $socket = $this->getResource();
  29. while (($length = strlen($value)) > 0) {
  30. $written = fwrite($socket, $value);
  31. if ($length === $written) {
  32. return true;
  33. }
  34. if ($written === false || $written === 0) {
  35. $this->onCommunicationException('Error while writing bytes to the server');
  36. }
  37. $value = substr($value, $written);
  38. }
  39. return true;
  40. }
  41. public function readBytes($length) {
  42. if ($length <= 0) {
  43. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  44. }
  45. $socket = $this->getResource();
  46. $value = '';
  47. do {
  48. $chunk = fread($socket, $length);
  49. if ($chunk === false || $chunk === '') {
  50. $this->onCommunicationException('Error while reading bytes from the server');
  51. }
  52. $value .= $chunk;
  53. }
  54. while (($length -= strlen($chunk)) > 0);
  55. return $value;
  56. }
  57. public function readLine() {
  58. $socket = $this->getResource();
  59. $value = '';
  60. do {
  61. $chunk = fgets($socket);
  62. if ($chunk === false || $chunk === '') {
  63. $this->onCommunicationException('Error while reading line from the server');
  64. }
  65. $value .= $chunk;
  66. }
  67. while (substr($value, -2) !== "\r\n");
  68. return substr($value, 0, -2);
  69. }
  70. public function writeCommand(ICommand $command) {
  71. $this->_protocol->write($this, $command);
  72. }
  73. public function read() {
  74. return $this->_protocol->read($this);
  75. }
  76. }