Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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;
  11. use InvalidArgumentException;
  12. use UnexpectedValueException;
  13. use Predis\Command\CommandInterface;
  14. use Predis\Command\RawCommand;
  15. use Predis\Command\ScriptCommand;
  16. use Predis\Configuration\Options;
  17. use Predis\Configuration\OptionsInterface;
  18. use Predis\Connection\ConnectionInterface;
  19. use Predis\Connection\AggregateConnectionInterface;
  20. use Predis\Connection\ParametersInterface;
  21. use Predis\Monitor\Consumer as MonitorConsumer;
  22. use Predis\Pipeline\Pipeline;
  23. use Predis\PubSub\Consumer as PubSubConsumer;
  24. use Predis\Response\ErrorInterface as ErrorResponseInterface;
  25. use Predis\Response\ResponseInterface;
  26. use Predis\Response\ServerException;
  27. use Predis\Transaction\MultiExec as MultiExecTransaction;
  28. /**
  29. * Client class used for connecting and executing commands on Redis.
  30. *
  31. * This is the main high-level abstraction of Predis upon which various other
  32. * abstractions are built. Internally it aggregates various other classes each
  33. * one with its own responsibility and scope.
  34. *
  35. * @author Daniele Alessandri <suppakilla@gmail.com>
  36. */
  37. class Client implements ClientInterface
  38. {
  39. const VERSION = '1.0.0-dev';
  40. protected $connection;
  41. protected $options;
  42. private $profile;
  43. /**
  44. * @param mixed $parameters Connection parameters for one or more servers.
  45. * @param mixed $options Options to configure some behaviours of the client.
  46. */
  47. public function __construct($parameters = null, $options = null)
  48. {
  49. $this->options = $this->createOptions($options ?: array());
  50. $this->connection = $this->createConnection($parameters ?: array());
  51. $this->profile = $this->options->profile;
  52. }
  53. /**
  54. * Creates a new instance of Predis\Configuration\Options from different
  55. * types of arguments or simply returns the passed argument if it is an
  56. * instance of Predis\Configuration\OptionsInterface.
  57. *
  58. * @param mixed $options Client options.
  59. * @return OptionsInterface
  60. */
  61. protected function createOptions($options)
  62. {
  63. if (is_array($options)) {
  64. return new Options($options);
  65. }
  66. if ($options instanceof OptionsInterface) {
  67. return $options;
  68. }
  69. throw new InvalidArgumentException("Invalid type for client options.");
  70. }
  71. /**
  72. * Creates single or aggregate connections from different types of arguments
  73. * (string, array) or returns the passed argument if it is an instance of a
  74. * class implementing Predis\Connection\ConnectionInterface.
  75. *
  76. * Accepted types for connection parameters are:
  77. *
  78. * - Instance of Predis\Connection\ConnectionInterface.
  79. * - Instance of Predis\Connection\ParametersInterface.
  80. * - Array
  81. * - String
  82. * - Callable
  83. *
  84. * @param mixed $parameters Connection parameters or connection instance.
  85. * @return ConnectionInterface
  86. */
  87. protected function createConnection($parameters)
  88. {
  89. if ($parameters instanceof ConnectionInterface) {
  90. return $parameters;
  91. }
  92. if ($parameters instanceof ParametersInterface || is_string($parameters)) {
  93. return $this->options->connections->create($parameters);
  94. }
  95. if (is_array($parameters)) {
  96. if (!isset($parameters[0])) {
  97. return $this->options->connections->create($parameters);
  98. }
  99. $options = $this->options;
  100. if ($options->defined('aggregate')) {
  101. $initializer = $this->getConnectionInitializerWrapper($options->aggregate);
  102. $connection = $initializer($parameters, $options);
  103. } else {
  104. if ($options->defined('replication') && $replication = $options->replication) {
  105. $connection = $replication;
  106. } else {
  107. $connection = $options->cluster;
  108. }
  109. $options->connections->aggregate($connection, $parameters);
  110. }
  111. return $connection;
  112. }
  113. if (is_callable($parameters)) {
  114. $initializer = $this->getConnectionInitializerWrapper($parameters);
  115. $connection = $initializer($this->options);
  116. return $connection;
  117. }
  118. throw new InvalidArgumentException('Invalid type for connection parameters.');
  119. }
  120. /**
  121. * Wraps a callable to make sure that its returned value represents a valid
  122. * connection type.
  123. *
  124. * @param mixed $callable
  125. * @return \Closure
  126. */
  127. protected function getConnectionInitializerWrapper($callable)
  128. {
  129. return function () use ($callable) {
  130. $connection = call_user_func_array($callable, func_get_args());
  131. if (!$connection instanceof ConnectionInterface) {
  132. throw new UnexpectedValueException(
  133. 'The callable connection initializer returned an invalid type.'
  134. );
  135. }
  136. return $connection;
  137. };
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function getProfile()
  143. {
  144. return $this->profile;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function getOptions()
  150. {
  151. return $this->options;
  152. }
  153. /**
  154. * Creates a new client instance for the specified connection ID or alias,
  155. * only when working with an aggregate connection (cluster, replication).
  156. * The new client instances uses the same options of the original one.
  157. *
  158. * @param string $connectionID Identifier of a connection.
  159. * @return Client
  160. */
  161. public function getClientFor($connectionID)
  162. {
  163. if (!$connection = $this->getConnectionById($connectionID)) {
  164. throw new InvalidArgumentException("Invalid connection ID: $connectionID.");
  165. }
  166. return new static($connection, $this->options);
  167. }
  168. /**
  169. * Opens the underlying connection and connects to the server.
  170. */
  171. public function connect()
  172. {
  173. $this->connection->connect();
  174. }
  175. /**
  176. * Closes the underlying connection and disconnects from the server.
  177. */
  178. public function disconnect()
  179. {
  180. $this->connection->disconnect();
  181. }
  182. /**
  183. * Closes the underlying connection and disconnects from the server.
  184. *
  185. * This is the same as `Client::disconnect()` as it does not actually send
  186. * the `QUIT` command to Redis, but simply closes the connection.
  187. */
  188. public function quit()
  189. {
  190. $this->disconnect();
  191. }
  192. /**
  193. * Returns the current state of the underlying connection.
  194. *
  195. * @return bool
  196. */
  197. public function isConnected()
  198. {
  199. return $this->connection->isConnected();
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function getConnection()
  205. {
  206. return $this->connection;
  207. }
  208. /**
  209. * Retrieves the specified connection from the aggregate connection when the
  210. * client is in cluster or replication mode.
  211. *
  212. * @param string $connectionID Index or alias of the single connection.
  213. * @return Connection\NodeConnectionInterface
  214. */
  215. public function getConnectionById($connectionID)
  216. {
  217. if (!$this->connection instanceof AggregateConnectionInterface) {
  218. throw new NotSupportedException(
  219. 'Retrieving connections by ID is supported only by aggregate connections.'
  220. );
  221. }
  222. return $this->connection->getConnectionById($connectionID);
  223. }
  224. /**
  225. * Executes a command without filtering its arguments, parsing the response,
  226. * applying any prefix to keys or throwing exceptions on Redis errors even
  227. * regardless of client options.
  228. *
  229. * It is possibile to indentify Redis error responses from normal responses
  230. * using the second optional argument which is populated by reference.
  231. *
  232. * @param array $arguments Command arguments as defined by the command signature.
  233. * @param bool $error Set to TRUE when Redis returned an error response.
  234. * @return mixed
  235. */
  236. public function executeRaw(array $arguments, &$error = null)
  237. {
  238. $error = false;
  239. $command = new RawCommand($arguments);
  240. $response = $this->connection->executeCommand($command);
  241. if ($response instanceof ResponseInterface) {
  242. if ($response instanceof ErrorResponseInterface) {
  243. $error = true;
  244. }
  245. return (string) $response;
  246. }
  247. return $response;
  248. }
  249. /**
  250. * Creates a Redis command with the specified arguments and sends a request
  251. * to the server.
  252. *
  253. * @param string $commandID Command ID.
  254. * @param array $arguments Arguments for the command.
  255. * @return mixed
  256. */
  257. public function __call($commandID, $arguments)
  258. {
  259. $command = $this->createCommand($commandID, $arguments);
  260. $response = $this->executeCommand($command);
  261. return $response;
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function createCommand($commandID, $arguments = array())
  267. {
  268. return $this->profile->createCommand($commandID, $arguments);
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function executeCommand(CommandInterface $command)
  274. {
  275. $response = $this->connection->executeCommand($command);
  276. if ($response instanceof ResponseInterface) {
  277. if ($response instanceof ErrorResponseInterface) {
  278. $response = $this->onErrorResponse($command, $response);
  279. }
  280. return $response;
  281. }
  282. return $command->parseResponse($response);
  283. }
  284. /**
  285. * Handles -ERR responses returned by Redis.
  286. *
  287. * @param CommandInterface $command Redis command that generated the error.
  288. * @param ErrorResponseInterface $response Instance of the error response.
  289. * @return mixed
  290. */
  291. protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response)
  292. {
  293. if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') {
  294. $eval = $this->createCommand('eval');
  295. $eval->setRawArguments($command->getEvalArguments());
  296. $response = $this->executeCommand($eval);
  297. if (!$response instanceof ResponseInterface) {
  298. $response = $command->parseResponse($response);
  299. }
  300. return $response;
  301. }
  302. if ($this->options->exceptions) {
  303. throw new ServerException($response->getMessage());
  304. }
  305. return $response;
  306. }
  307. /**
  308. * Executes the specified initializer method on `$this` by adjusting the
  309. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  310. * simply an utility method to create Redis contexts instances since they
  311. * follow a common initialization path.
  312. *
  313. * @param string $initializer Method name.
  314. * @param array $argv Arguments for the method.
  315. * @return mixed
  316. */
  317. private function sharedContextFactory($initializer, $argv = null)
  318. {
  319. switch (count($argv)) {
  320. case 0:
  321. return $this->$initializer();
  322. case 1:
  323. return is_array($argv[0])
  324. ? $this->$initializer($argv[0])
  325. : $this->$initializer(null, $argv[0]);
  326. case 2:
  327. list($arg0, $arg1) = $argv;
  328. return $this->$initializer($arg0, $arg1);
  329. default:
  330. return $this->$initializer($this, $argv);
  331. }
  332. }
  333. /**
  334. * Creates a new pipeline context and returns it, or returns the results of
  335. * a pipeline executed inside the optionally provided callable object.
  336. *
  337. * @param mixed ... Array of options, a callable for execution, or both.
  338. * @return Pipeline|array
  339. */
  340. public function pipeline(/* arguments */)
  341. {
  342. return $this->sharedContextFactory('createPipeline', func_get_args());
  343. }
  344. /**
  345. * Actual pipeline context initializer method.
  346. *
  347. * @param array $options Options for the context.
  348. * @param mixed $callable Optional callable used to execute the context.
  349. * @return Pipeline|array
  350. */
  351. protected function createPipeline(array $options = null, $callable = null)
  352. {
  353. if (isset($options['atomic']) && $options['atomic']) {
  354. $class = 'Predis\Pipeline\Atomic';
  355. } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
  356. $class = 'Predis\Pipeline\FireAndForget';
  357. } else {
  358. $class = 'Predis\Pipeline\Pipeline';
  359. }
  360. $pipeline = new $class($this);
  361. if (isset($callable)) {
  362. return $pipeline->execute($callable);
  363. }
  364. return $pipeline;
  365. }
  366. /**
  367. * Creates a new transaction context and returns it, or returns the results
  368. * of a transaction executed inside the optionally provided callable object.
  369. *
  370. * @param mixed ... Array of options, a callable for execution, or both.
  371. * @return MultiExecTransaction|array
  372. */
  373. public function transaction(/* arguments */)
  374. {
  375. return $this->sharedContextFactory('createTransaction', func_get_args());
  376. }
  377. /**
  378. * Actual transaction context initializer method.
  379. *
  380. * @param array $options Options for the context.
  381. * @param mixed $callable Optional callable used to execute the context.
  382. * @return MultiExecTransaction|array
  383. */
  384. protected function createTransaction(array $options = null, $callable = null)
  385. {
  386. $transaction = new MultiExecTransaction($this, $options);
  387. if (isset($callable)) {
  388. return $transaction->execute($callable);
  389. }
  390. return $transaction;
  391. }
  392. /**
  393. * Creates a new publis/subscribe context and returns it, or starts its loop
  394. * inside the optionally provided callable object.
  395. *
  396. * @param mixed ... Array of options, a callable for execution, or both.
  397. * @return PubSubConsumer|NULL
  398. */
  399. public function pubSubLoop(/* arguments */)
  400. {
  401. return $this->sharedContextFactory('createPubSub', func_get_args());
  402. }
  403. /**
  404. * Actual publish/subscribe context initializer method.
  405. *
  406. * @param array $options Options for the context.
  407. * @param mixed $callable Optional callable used to execute the context.
  408. * @return PubSubConsumer|NULL
  409. */
  410. protected function createPubSub(array $options = null, $callable = null)
  411. {
  412. $pubsub = new PubSubConsumer($this, $options);
  413. if (!isset($callable)) {
  414. return $pubsub;
  415. }
  416. foreach ($pubsub as $message) {
  417. if (call_user_func($callable, $pubsub, $message) === false) {
  418. $pubsub->stop();
  419. }
  420. }
  421. }
  422. /**
  423. * Creates a new monitor consumer and returns it.
  424. *
  425. * @return MonitorConsumer
  426. */
  427. public function monitor()
  428. {
  429. return new MonitorConsumer($this);
  430. }
  431. }