Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 TransactionMultiExec;
  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 = '0.9.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. * @return Client
  159. */
  160. public function getClientFor($connectionID)
  161. {
  162. if (!$connection = $this->getConnectionById($connectionID)) {
  163. throw new InvalidArgumentException("Invalid connection ID: $connectionID.");
  164. }
  165. return new static($connection, $this->options);
  166. }
  167. /**
  168. * Opens the underlying connection and connects to the server.
  169. */
  170. public function connect()
  171. {
  172. $this->connection->connect();
  173. }
  174. /**
  175. * Closes the underlying connection and disconnects from the server.
  176. */
  177. public function disconnect()
  178. {
  179. $this->connection->disconnect();
  180. }
  181. /**
  182. * Closes the underlying connection and disconnects from the server.
  183. *
  184. * This is the same as `Client::disconnect()` as it does not actually send
  185. * the `QUIT` command to Redis, but simply closes the connection.
  186. */
  187. public function quit()
  188. {
  189. $this->disconnect();
  190. }
  191. /**
  192. * Returns the current state of the underlying connection.
  193. *
  194. * @return bool
  195. */
  196. public function isConnected()
  197. {
  198. return $this->connection->isConnected();
  199. }
  200. /**
  201. * {@inheritdoc}
  202. */
  203. public function getConnection()
  204. {
  205. return $this->connection;
  206. }
  207. /**
  208. * Retrieves the specified connection from the aggregate connection when the
  209. * client is in cluster or replication mode.
  210. *
  211. * @param string $connectionID Index or alias of the single connection.
  212. * @return Connection\SingleConnectionInterface
  213. */
  214. public function getConnectionById($connectionID)
  215. {
  216. if (!$this->connection instanceof AggregateConnectionInterface) {
  217. throw new NotSupportedException(
  218. 'Retrieving connections by ID is supported only by aggregate connections.'
  219. );
  220. }
  221. return $this->connection->getConnectionById($connectionID);
  222. }
  223. /**
  224. * Executes a command without filtering its arguments, parsing the response,
  225. * applying any prefix to keys or throwing exceptions on Redis errors even
  226. * regardless of client options.
  227. *
  228. * It is possibile to indentify Redis error responses from normal responses
  229. * using the second optional argument which is populated by reference.
  230. *
  231. * @param array $arguments Command arguments as defined by the command signature.
  232. * @param bool $error Set to TRUE when Redis returned an error response.
  233. * @return mixed
  234. */
  235. public function executeRaw(array $arguments, &$error = null)
  236. {
  237. $error = false;
  238. $command = new RawCommand($arguments);
  239. $response = $this->connection->executeCommand($command);
  240. if ($response instanceof ResponseInterface) {
  241. if ($response instanceof ErrorResponseInterface) {
  242. $error = true;
  243. }
  244. return (string) $response;
  245. }
  246. return $response;
  247. }
  248. /**
  249. * Creates a Redis command with the specified arguments and sends a request
  250. * to the server.
  251. *
  252. * @param string $commandID Command ID.
  253. * @param array $arguments Arguments for the command.
  254. * @return mixed
  255. */
  256. public function __call($commandID, $arguments)
  257. {
  258. $command = $this->createCommand($commandID, $arguments);
  259. $response = $this->executeCommand($command);
  260. return $response;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function createCommand($commandID, $arguments = array())
  266. {
  267. return $this->profile->createCommand($commandID, $arguments);
  268. }
  269. /**
  270. * {@inheritdoc}
  271. */
  272. public function executeCommand(CommandInterface $command)
  273. {
  274. $response = $this->connection->executeCommand($command);
  275. if ($response instanceof ResponseInterface) {
  276. if ($response instanceof ErrorResponseInterface) {
  277. $response = $this->onErrorResponse($command, $response);
  278. }
  279. return $response;
  280. }
  281. return $command->parseResponse($response);
  282. }
  283. /**
  284. * Handles -ERR responses returned by Redis.
  285. *
  286. * @param CommandInterface $command Redis command that generated the error.
  287. * @param ErrorResponseInterface $response Instance of the error response.
  288. * @return mixed
  289. */
  290. protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response)
  291. {
  292. if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') {
  293. $eval = $this->createCommand('eval');
  294. $eval->setRawArguments($command->getEvalArguments());
  295. $response = $this->executeCommand($eval);
  296. if (!$response instanceof ResponseInterface) {
  297. $response = $command->parseResponse($response);
  298. }
  299. return $response;
  300. }
  301. if ($this->options->exceptions) {
  302. throw new ServerException($response->getMessage());
  303. }
  304. return $response;
  305. }
  306. /**
  307. * Executes the specified initializer method on `$this` by adjusting the
  308. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  309. * simply an utility method to create Redis contexts instances since they
  310. * follow a common initialization path.
  311. *
  312. * @param string $initializer Method name.
  313. * @param array $argv Arguments for the method.
  314. * @return mixed
  315. */
  316. private function sharedContextFactory($initializer, $argv = null)
  317. {
  318. switch (count($argv)) {
  319. case 0:
  320. return $this->$initializer();
  321. case 1:
  322. return is_array($argv[0])
  323. ? $this->$initializer($argv[0])
  324. : $this->$initializer(null, $argv[0]);
  325. case 2:
  326. list($arg0, $arg1) = $argv;
  327. return $this->$initializer($arg0, $arg1);
  328. default:
  329. return $this->$initializer($this, $argv);
  330. }
  331. }
  332. /**
  333. * Creates a new pipeline context and returns it, or returns the results of
  334. * a pipeline executed inside the optionally provided callable object.
  335. *
  336. * @param mixed $arg,... Array of options, a callable for execution, or both.
  337. * @return Pipeline|array
  338. */
  339. public function pipeline(/* arguments */)
  340. {
  341. return $this->sharedContextFactory('createPipeline', func_get_args());
  342. }
  343. /**
  344. * Actual pipeline context initializer method.
  345. *
  346. * @param array $options Options for the context.
  347. * @param mixed $callable Optional callable used to execute the context.
  348. * @return Pipeline|array
  349. */
  350. protected function createPipeline(array $options = null, $callable = null)
  351. {
  352. if (isset($options['atomic']) && $options['atomic']) {
  353. $class = 'Predis\Pipeline\Atomic';
  354. } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
  355. $class = 'Predis\Pipeline\FireAndForget';
  356. } else {
  357. $class = 'Predis\Pipeline\Pipeline';
  358. }
  359. $pipeline = new $class($this);
  360. if (isset($callable)) {
  361. return $pipeline->execute($callable);
  362. }
  363. return $pipeline;
  364. }
  365. /**
  366. * Creates a new transaction context and returns it, or returns the results
  367. * of a transaction executed inside the optionally provided callable object.
  368. *
  369. * @param mixed $arg,... Array of options, a callable for execution, or both.
  370. * @return TransactionMultiExec|array
  371. */
  372. public function transaction(/* arguments */)
  373. {
  374. return $this->sharedContextFactory('createTransaction', func_get_args());
  375. }
  376. /**
  377. * Actual transaction context initializer method.
  378. *
  379. * @param array $options Options for the context.
  380. * @param mixed $callable Optional callable used to execute the context.
  381. * @return TransactionMultiExec|array
  382. */
  383. protected function createTransaction(array $options = null, $callable = null)
  384. {
  385. $transaction = new TransactionMultiExec($this, $options);
  386. if (isset($callable)) {
  387. return $transaction->execute($callable);
  388. }
  389. return $transaction;
  390. }
  391. /**
  392. * Creates a new publis/subscribe context and returns it, or starts its loop
  393. * inside the optionally provided callable object.
  394. *
  395. * @param mixed $arg,... Array of options, a callable for execution, or both.
  396. * @return PubSubConsumer|NULL
  397. */
  398. public function pubSubLoop(/* arguments */)
  399. {
  400. return $this->sharedContextFactory('createPubSub', func_get_args());
  401. }
  402. /**
  403. * Actual publish/subscribe context initializer method.
  404. *
  405. * @param array $options Options for the context.
  406. * @param mixed $callable Optional callable used to execute the context.
  407. * @return PubSubConsumer|NULL
  408. */
  409. protected function createPubSub(array $options = null, $callable = null)
  410. {
  411. $pubsub = new PubSubConsumer($this, $options);
  412. if (!isset($callable)) {
  413. return $pubsub;
  414. }
  415. foreach ($pubsub as $message) {
  416. if (call_user_func($callable, $pubsub, $message) === false) {
  417. $pubsub->stop();
  418. }
  419. }
  420. }
  421. /**
  422. * Creates a new monitor consumer and returns it.
  423. *
  424. * @return MonitorConsumer
  425. */
  426. public function monitor()
  427. {
  428. return new MonitorConsumer($this);
  429. }
  430. }