ComposableStreamConnection.php 2.6 KB

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