StreamConnection.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\ICommand;
  4. use Predis\ResponseError;
  5. use Predis\ResponseQueued;
  6. use Predis\ServerException;
  7. use Predis\ConnectionParameters;
  8. use Predis\CommunicationException;
  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. $timeoutSeconds = floor($parameters->read_write_timeout);
  60. $timeoutUSeconds = ($parameters->read_write_timeout - $timeoutSeconds) * 1000000;
  61. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  62. }
  63. return $resource;
  64. }
  65. private function unixStreamInitializer(ConnectionParameters $parameters) {
  66. $uri = sprintf('unix:///%s', $parameters->path);
  67. $flags = STREAM_CLIENT_CONNECT;
  68. if ($parameters->connection_persistent) {
  69. $flags |= STREAM_CLIENT_PERSISTENT;
  70. }
  71. $resource = @stream_socket_client(
  72. $uri, $errno, $errstr, $parameters->connection_timeout, $flags
  73. );
  74. if (!$resource) {
  75. $this->onCommunicationException(trim($errstr), $errno);
  76. }
  77. return $resource;
  78. }
  79. public function connect() {
  80. parent::connect();
  81. if (count($this->_initCmds) > 0){
  82. $this->sendInitializationCommands();
  83. }
  84. }
  85. public function disconnect() {
  86. if ($this->isConnected()) {
  87. fclose($this->getResource());
  88. }
  89. }
  90. private function sendInitializationCommands() {
  91. foreach ($this->_initCmds as $command) {
  92. $this->writeCommand($command);
  93. }
  94. foreach ($this->_initCmds as $command) {
  95. $this->readResponse($command);
  96. }
  97. }
  98. private function write($buffer) {
  99. $socket = $this->getResource();
  100. while (($length = strlen($buffer)) > 0) {
  101. $written = fwrite($socket, $buffer);
  102. if ($length === $written) {
  103. return;
  104. }
  105. if ($written === false || $written === 0) {
  106. $this->onCommunicationException(
  107. 'Error while writing bytes to the server'
  108. );
  109. }
  110. $value = substr($buffer, $written);
  111. }
  112. }
  113. public function read() {
  114. $socket = $this->getResource();
  115. $chunk = fgets($socket);
  116. if ($chunk === false || $chunk === '') {
  117. $this->onCommunicationException(
  118. 'Error while reading line from the server'
  119. );
  120. }
  121. $prefix = $chunk[0];
  122. $payload = substr($chunk, 1, -2);
  123. switch ($prefix) {
  124. case '+': // inline
  125. switch ($payload) {
  126. case 'OK':
  127. return true;
  128. case 'QUEUED':
  129. return new ResponseQueued();
  130. default:
  131. return $payload;
  132. }
  133. case '$': // bulk
  134. $size = (int) $payload;
  135. if ($size === -1) {
  136. return null;
  137. }
  138. $bulkData = '';
  139. $bytesLeft = ($size += 2);
  140. do {
  141. $chunk = fread($socket, min($bytesLeft, 4096));
  142. if ($chunk === false || $chunk === '') {
  143. $this->onCommunicationException(
  144. 'Error while reading bytes from the server'
  145. );
  146. }
  147. $bulkData .= $chunk;
  148. $bytesLeft = $size - strlen($bulkData);
  149. } while ($bytesLeft > 0);
  150. return substr($bulkData, 0, -2);
  151. case '*': // multi bulk
  152. $count = (int) $payload;
  153. if ($count === -1) {
  154. return null;
  155. }
  156. if ($this->_mbiterable === true) {
  157. return new MultiBulkResponseSimple($this, $count);
  158. }
  159. $multibulk = array();
  160. for ($i = 0; $i < $count; $i++) {
  161. $multibulk[$i] = $this->read();
  162. }
  163. return $multibulk;
  164. case ':': // integer
  165. return (int) $payload;
  166. case '-': // error
  167. $errorMessage = substr($payload, 4);
  168. if ($this->_throwErrors) {
  169. throw new ServerException($errorMessage);
  170. }
  171. return new ResponseError($errorMessage);
  172. default:
  173. $this->onCommunicationException("Unknown prefix: '$prefix'");
  174. }
  175. }
  176. public function writeCommand(ICommand $command) {
  177. $this->write($this->_commandSerializer->serialize($command));
  178. }
  179. public function readResponse(ICommand $command) {
  180. $reply = $this->read();
  181. return isset($reply->skipParse) ? $reply : $command->parseResponse($reply);
  182. }
  183. public function setProtocolOption($option, $value) {
  184. switch ($option) {
  185. case 'iterable_multibulk':
  186. $this->_mbiterable = (bool) $value;
  187. break;
  188. case 'throw_errors':
  189. $this->_throwErrors = (bool) $value;
  190. break;
  191. }
  192. }
  193. }