ComposableStreamConnection.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\ConnectionParameters;
  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(ConnectionParameters $parameters, IProtocolProcessor $protocol = null) {
  11. $this->setProtocol($protocol ?: new TextProtocol());
  12. parent::__construct($parameters);
  13. }
  14. public function setProtocol(IProtocolProcessor $protocol) {
  15. if ($protocol === null) {
  16. throw new \InvalidArgumentException("The protocol instance cannot be a null value");
  17. }
  18. $this->_protocol = $protocol;
  19. }
  20. public function getProtocol() {
  21. return $this->_protocol;
  22. }
  23. public function setProtocolOption($option, $value) {
  24. return $this->_protocol->setOption($option, $value);
  25. }
  26. public function writeBytes($value) {
  27. $socket = $this->getResource();
  28. while (($length = strlen($value)) > 0) {
  29. $written = fwrite($socket, $value);
  30. if ($length === $written) {
  31. return true;
  32. }
  33. if ($written === false || $written === 0) {
  34. $this->onCommunicationException('Error while writing bytes to the server');
  35. }
  36. $value = substr($value, $written);
  37. }
  38. return true;
  39. }
  40. public function readBytes($length) {
  41. if ($length <= 0) {
  42. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  43. }
  44. $socket = $this->getResource();
  45. $value = '';
  46. do {
  47. $chunk = fread($socket, $length);
  48. if ($chunk === false || $chunk === '') {
  49. $this->onCommunicationException('Error while reading bytes from the server');
  50. }
  51. $value .= $chunk;
  52. }
  53. while (($length -= strlen($chunk)) > 0);
  54. return $value;
  55. }
  56. public function readLine() {
  57. $socket = $this->getResource();
  58. $value = '';
  59. do {
  60. $chunk = fgets($socket);
  61. if ($chunk === false || $chunk === '') {
  62. $this->onCommunicationException('Error while reading line from the server');
  63. }
  64. $value .= $chunk;
  65. }
  66. while (substr($value, -2) !== "\r\n");
  67. return substr($value, 0, -2);
  68. }
  69. public function writeCommand(ICommand $command) {
  70. $this->_protocol->write($this, $command);
  71. }
  72. public function read() {
  73. return $this->_protocol->read($this);
  74. }
  75. }