StreamConnection.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\ResponseError;
  4. use Predis\ResponseQueued;
  5. use Predis\ServerException;
  6. use Predis\ConnectionParameters;
  7. use Predis\CommunicationException;
  8. use Predis\Commands\ICommand;
  9. use Predis\Protocols\TextCommandSerializer;
  10. use Predis\Iterators\MultiBulkResponseSimple;
  11. class StreamConnection extends ConnectionBase {
  12. private $_commandSerializer, $_mbiterable, $_throwErrors;
  13. public function __construct(ConnectionParameters $parameters) {
  14. parent::__construct($this->checkParameters($parameters));
  15. $this->_commandSerializer = new TextCommandSerializer();
  16. }
  17. public function __destruct() {
  18. if (!$this->_params->connection_persistent) {
  19. $this->disconnect();
  20. }
  21. }
  22. protected function checkParameters(ConnectionParameters $parameters) {
  23. switch ($parameters->scheme) {
  24. case 'unix':
  25. $pathToSocket = $parameters->path;
  26. if (!isset($pathToSocket)) {
  27. throw new \InvalidArgumentException('Missing UNIX domain socket path');
  28. }
  29. if (!file_exists($pathToSocket)) {
  30. throw new \InvalidArgumentException("Could not find $pathToSocket");
  31. }
  32. case 'tcp':
  33. return $parameters;
  34. default:
  35. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  36. }
  37. }
  38. protected function createResource() {
  39. $parameters = $this->_params;
  40. $initializer = array($this, "{$parameters->scheme}StreamInitializer");
  41. return call_user_func($initializer, $parameters);
  42. }
  43. private function tcpStreamInitializer(ConnectionParameters $parameters) {
  44. $uri = sprintf('tcp://%s:%d/', $parameters->host, $parameters->port);
  45. $flags = STREAM_CLIENT_CONNECT;
  46. if ($parameters->connection_async) {
  47. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  48. }
  49. if ($parameters->connection_persistent) {
  50. $flags |= STREAM_CLIENT_PERSISTENT;
  51. }
  52. $resource = @stream_socket_client(
  53. $uri, $errno, $errstr, $parameters->connection_timeout, $flags
  54. );
  55. if (!$resource) {
  56. $this->onCommunicationException(trim($errstr), $errno);
  57. }
  58. if (isset($parameters->read_write_timeout)) {
  59. $rwtimeout = $parameters->read_write_timeout;
  60. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  61. $timeoutSeconds = floor($rwtimeout);
  62. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  63. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  64. }
  65. return $resource;
  66. }
  67. private function unixStreamInitializer(ConnectionParameters $parameters) {
  68. $uri = sprintf('unix:///%s', $parameters->path);
  69. $flags = STREAM_CLIENT_CONNECT;
  70. if ($parameters->connection_persistent) {
  71. $flags |= STREAM_CLIENT_PERSISTENT;
  72. }
  73. $resource = @stream_socket_client(
  74. $uri, $errno, $errstr, $parameters->connection_timeout, $flags
  75. );
  76. if (!$resource) {
  77. $this->onCommunicationException(trim($errstr), $errno);
  78. }
  79. return $resource;
  80. }
  81. public function connect() {
  82. parent::connect();
  83. if (count($this->_initCmds) > 0){
  84. $this->sendInitializationCommands();
  85. }
  86. }
  87. public function disconnect() {
  88. if ($this->isConnected()) {
  89. fclose($this->getResource());
  90. }
  91. }
  92. private function sendInitializationCommands() {
  93. foreach ($this->_initCmds as $command) {
  94. $this->writeCommand($command);
  95. }
  96. foreach ($this->_initCmds as $command) {
  97. $this->readResponse($command);
  98. }
  99. }
  100. private function write($buffer) {
  101. $socket = $this->getResource();
  102. while (($length = strlen($buffer)) > 0) {
  103. $written = fwrite($socket, $buffer);
  104. if ($length === $written) {
  105. return;
  106. }
  107. if ($written === false || $written === 0) {
  108. $this->onCommunicationException(
  109. 'Error while writing bytes to the server'
  110. );
  111. }
  112. $value = substr($buffer, $written);
  113. }
  114. }
  115. public function read() {
  116. $socket = $this->getResource();
  117. $chunk = fgets($socket);
  118. if ($chunk === false || $chunk === '') {
  119. $this->onCommunicationException(
  120. 'Error while reading line from the server'
  121. );
  122. }
  123. $prefix = $chunk[0];
  124. $payload = substr($chunk, 1, -2);
  125. switch ($prefix) {
  126. case '+': // inline
  127. switch ($payload) {
  128. case 'OK':
  129. return true;
  130. case 'QUEUED':
  131. return new ResponseQueued();
  132. default:
  133. return $payload;
  134. }
  135. case '$': // bulk
  136. $size = (int) $payload;
  137. if ($size === -1) {
  138. return null;
  139. }
  140. $bulkData = '';
  141. $bytesLeft = ($size += 2);
  142. do {
  143. $chunk = fread($socket, min($bytesLeft, 4096));
  144. if ($chunk === false || $chunk === '') {
  145. $this->onCommunicationException(
  146. 'Error while reading bytes from the server'
  147. );
  148. }
  149. $bulkData .= $chunk;
  150. $bytesLeft = $size - strlen($bulkData);
  151. } while ($bytesLeft > 0);
  152. return substr($bulkData, 0, -2);
  153. case '*': // multi bulk
  154. $count = (int) $payload;
  155. if ($count === -1) {
  156. return null;
  157. }
  158. if ($this->_mbiterable === true) {
  159. return new MultiBulkResponseSimple($this, $count);
  160. }
  161. $multibulk = array();
  162. for ($i = 0; $i < $count; $i++) {
  163. $multibulk[$i] = $this->read();
  164. }
  165. return $multibulk;
  166. case ':': // integer
  167. return (int) $payload;
  168. case '-': // error
  169. $errorMessage = substr($payload, 4);
  170. if ($this->_throwErrors) {
  171. throw new ServerException($errorMessage);
  172. }
  173. return new ResponseError($errorMessage);
  174. default:
  175. $this->onCommunicationException("Unknown prefix: '$prefix'");
  176. }
  177. }
  178. public function writeCommand(ICommand $command) {
  179. $this->write($this->_commandSerializer->serialize($command));
  180. }
  181. public function readResponse(ICommand $command) {
  182. $reply = $this->read();
  183. return isset($reply->skipParse) ? $reply : $command->parseResponse($reply);
  184. }
  185. public function setProtocolOption($option, $value) {
  186. switch ($option) {
  187. case 'iterable_multibulk':
  188. $this->_mbiterable = (bool) $value;
  189. break;
  190. case 'throw_errors':
  191. $this->_throwErrors = (bool) $value;
  192. break;
  193. }
  194. }
  195. }