Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 mixed
  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 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(
  291. CommandInterface $command,
  292. ErrorResponseInterface $response
  293. ) {
  294. if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') {
  295. $eval = $this->createCommand('eval');
  296. $eval->setRawArguments($command->getEvalArguments());
  297. $response = $this->executeCommand($eval);
  298. if (!$response instanceof ResponseInterface) {
  299. $response = $command->parseResponse($response);
  300. }
  301. return $response;
  302. }
  303. if ($this->options->exceptions) {
  304. throw new ServerException($response->getMessage());
  305. }
  306. return $response;
  307. }
  308. /**
  309. * Executes the specified initializer method on `$this` by adjusting the
  310. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  311. * simply an utility method to create Redis contexts instances since they
  312. * follow a common initialization path.
  313. *
  314. * @param string $initializer Method name.
  315. * @param array $argv Arguments for the method.
  316. * @return mixed
  317. */
  318. private function sharedContextFactory($initializer, $argv = null)
  319. {
  320. switch (count($argv)) {
  321. case 0:
  322. return $this->$initializer();
  323. case 1:
  324. return is_array($argv[0])
  325. ? $this->$initializer($argv[0])
  326. : $this->$initializer(null, $argv[0]);
  327. case 2:
  328. list($arg0, $arg1) = $argv;
  329. return $this->$initializer($arg0, $arg1);
  330. default:
  331. return $this->$initializer($this, $argv);
  332. }
  333. }
  334. /**
  335. * Creates a new pipeline context and returns it, or returns the results of
  336. * a pipeline executed inside the optionally provided callable object.
  337. *
  338. * @param mixed $arg,... Options for the context, or a callable, or both.
  339. * @return Pipeline|array
  340. */
  341. public function pipeline(/* arguments */)
  342. {
  343. return $this->sharedContextFactory('createPipeline', func_get_args());
  344. }
  345. /**
  346. * Actual pipeline context initializer method.
  347. *
  348. * @param array $options Options for the context.
  349. * @param mixed $callable Optional callable used to execute the context.
  350. * @return Pipeline|array
  351. */
  352. protected function createPipeline(array $options = null, $callable = null)
  353. {
  354. if (isset($options['atomic']) && $options['atomic']) {
  355. $class = 'Predis\Pipeline\Atomic';
  356. } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
  357. $class = 'Predis\Pipeline\FireAndForget';
  358. } else {
  359. $class = 'Predis\Pipeline\Pipeline';
  360. }
  361. $pipeline = new $class($this);
  362. if (isset($callable)) {
  363. return $pipeline->execute($callable);
  364. }
  365. return $pipeline;
  366. }
  367. /**
  368. * Creates a new transaction context and returns it, or returns the results
  369. * of a transaction executed inside the optionally provided callable object.
  370. *
  371. * @param mixed $arg,... Options for the context, or a callable, or both.
  372. * @return TransactionMultiExec|array
  373. */
  374. public function transaction(/* arguments */)
  375. {
  376. return $this->sharedContextFactory('createTransaction', func_get_args());
  377. }
  378. /**
  379. * Actual transaction context initializer method.
  380. *
  381. * @param array $options Options for the context.
  382. * @param mixed $callable Optional callable used to execute the context.
  383. * @return TransactionMultiExec|array
  384. */
  385. protected function createTransaction(array $options = null, $callable = null)
  386. {
  387. $transaction = new TransactionMultiExec($this, $options);
  388. if (isset($callable)) {
  389. return $transaction->execute($callable);
  390. }
  391. return $transaction;
  392. }
  393. /**
  394. * Creates a new publis/subscribe context and returns it, or starts its loop
  395. * inside the optionally provided callable object.
  396. *
  397. * @param mixed $arg,... Options for the context, or a callable, or both.
  398. * @return PubSubConsumer|NULL
  399. */
  400. public function pubSubLoop(/* arguments */)
  401. {
  402. return $this->sharedContextFactory('createPubSub', func_get_args());
  403. }
  404. /**
  405. * Actual publish/subscribe context initializer method.
  406. *
  407. * @param array $options Options for the context.
  408. * @param mixed $callable Optional callable used to execute the context.
  409. * @return PubSubConsumer|NULL
  410. */
  411. protected function createPubSub(array $options = null, $callable = null)
  412. {
  413. $pubsub = new PubSubConsumer($this, $options);
  414. if (!isset($callable)) {
  415. return $pubsub;
  416. }
  417. foreach ($pubsub as $message) {
  418. if (call_user_func($callable, $pubsub, $message) === false) {
  419. $pubsub->stop();
  420. }
  421. }
  422. }
  423. /**
  424. * Creates a new monitor consumer and returns it.
  425. *
  426. * @return MonitorConsumer
  427. */
  428. public function monitor()
  429. {
  430. return new MonitorConsumer($this);
  431. }
  432. }