Client.php 15 KB

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