Client.php 16 KB

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