Client.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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\ConnectionInterface;
  17. use Predis\Connection\ParametersInterface;
  18. use Predis\Connection\Replication\SentinelReplication;
  19. use Predis\Monitor\Consumer as MonitorConsumer;
  20. use Predis\Pipeline\Pipeline;
  21. use Predis\PubSub\Consumer as PubSubConsumer;
  22. use Predis\Response\ErrorInterface as ErrorResponseInterface;
  23. use Predis\Response\ResponseInterface;
  24. use Predis\Response\ServerException;
  25. use Predis\Transaction\MultiExec as MultiExecTransaction;
  26. /**
  27. * Client class used for connecting and executing commands on Redis.
  28. *
  29. * This is the main high-level abstraction of Predis upon which various other
  30. * abstractions are built. Internally it aggregates various other classes each
  31. * one with its own responsibility and scope.
  32. *
  33. * {@inheritdoc}
  34. *
  35. * @author Daniele Alessandri <suppakilla@gmail.com>
  36. */
  37. class Client implements ClientInterface, \IteratorAggregate
  38. {
  39. const VERSION = '2.0.0-dev';
  40. /**
  41. * @var Predis\Configuration\OptionsInterface
  42. */
  43. private $options;
  44. /**
  45. * @var Predis\Connection\ConnectionInterface
  46. */
  47. private $connection;
  48. /**
  49. * @var Predis\Command\FactoryInterface
  50. */
  51. private $commands;
  52. /**
  53. * @param mixed $parameters Connection parameters for one or more servers.
  54. * @param mixed $options Options to configure some behaviours of the client.
  55. */
  56. public function __construct($parameters = null, $options = null)
  57. {
  58. $this->options = $this->createOptions($options ?: array());
  59. $this->connection = $this->createConnection($parameters ?: array());
  60. $this->commands = $this->options->commands;
  61. }
  62. /**
  63. * Creates a new instance of Predis\Configuration\Options from different
  64. * types of arguments or simply returns the passed argument if it is an
  65. * instance of Predis\Configuration\OptionsInterface.
  66. *
  67. * @param mixed $options Client options.
  68. *
  69. * @throws \InvalidArgumentException
  70. *
  71. * @return OptionsInterface
  72. */
  73. protected function createOptions($options)
  74. {
  75. if (is_array($options)) {
  76. return new Options($options);
  77. }
  78. if ($options instanceof OptionsInterface) {
  79. return $options;
  80. }
  81. throw new \InvalidArgumentException('Invalid type for client options');
  82. }
  83. /**
  84. * Creates single or aggregate connections from different types of arguments
  85. * (string, array) or returns the passed argument if it is an instance of a
  86. * class implementing Predis\Connection\ConnectionInterface.
  87. *
  88. * Accepted types for connection parameters are:
  89. *
  90. * - Instance of Predis\Connection\ConnectionInterface.
  91. * - Instance of Predis\Connection\ParametersInterface.
  92. * - Array
  93. * - String
  94. * - Callable
  95. *
  96. * @param mixed $parameters Connection parameters or connection instance.
  97. *
  98. * @throws \InvalidArgumentException
  99. *
  100. * @return ConnectionInterface
  101. */
  102. protected function createConnection($parameters)
  103. {
  104. $options = $this->getOptions();
  105. if ($parameters instanceof ConnectionInterface) {
  106. return $parameters;
  107. }
  108. if ($parameters instanceof ParametersInterface || is_string($parameters)) {
  109. return $options->connections->create($parameters);
  110. }
  111. if (is_array($parameters)) {
  112. if (!isset($parameters[0])) {
  113. return $options->connections->create($parameters);
  114. }
  115. if ($options->defined('cluster')) {
  116. return $this->createAggregateConnection($parameters, 'cluster');
  117. } elseif ($options->defined('replication')) {
  118. return $this->createAggregateConnection($parameters, 'replication');
  119. } elseif ($options->defined('aggregate')) {
  120. return $this->createAggregateConnection($parameters, 'aggregate');
  121. } else {
  122. throw new \InvalidArgumentException(
  123. 'Array of connection parameters requires `cluster`, `replication` or `aggregate` client option'
  124. );
  125. }
  126. }
  127. if (is_callable($parameters)) {
  128. $connection = call_user_func($parameters, $options);
  129. if (!$connection instanceof ConnectionInterface) {
  130. throw new \InvalidArgumentException('Callable parameters must return a valid connection');
  131. }
  132. return $connection;
  133. }
  134. throw new \InvalidArgumentException('Invalid type for connection parameters');
  135. }
  136. /**
  137. * Creates an aggregate connection.
  138. *
  139. * @param mixed $parameters Connection parameters.
  140. * @param string $option Option for aggregate connections (`aggregate`, `cluster`, `replication`).
  141. *
  142. * @return \Closure
  143. */
  144. protected function createAggregateConnection($parameters, $option)
  145. {
  146. $options = $this->getOptions();
  147. $initializer = $options->$option;
  148. $connection = $initializer($parameters);
  149. // TODO: this is dirty but we must skip the redis-sentinel backend for now.
  150. if ($option !== 'aggregate' && !$connection instanceof SentinelReplication) {
  151. $options->connections->aggregate($connection, $parameters);
  152. }
  153. return $connection;
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function getCommandFactory()
  159. {
  160. return $this->commands;
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function getOptions()
  166. {
  167. return $this->options;
  168. }
  169. /**
  170. * Creates a new client from the specified .
  171. *
  172. * The new client instances inherites the same options of the original one.
  173. * When no callable object is supplied, this method returns the new client.
  174. * When a callable object is supplied, the new client is passed as its sole
  175. * argument and its return value is returned by this method to the caller.
  176. *
  177. * NOTE: This method works against any kind of underlying connection object
  178. * as it uses a duck-typing approach and looks for a suitable method that
  179. * matches the selector type to extract the correct connection.
  180. *
  181. * @param string $selector Type of selector (`id`, `key`, `slot`, `command`)
  182. * @param string $value Values of selector.
  183. * @param callable|null $callable Optional callable object.
  184. *
  185. * @return ClientInterface|mixed
  186. */
  187. public function getClientBy($selector, $value, $callable = null)
  188. {
  189. $selector = strtolower($selector);
  190. if (!in_array($selector, array('id', 'key', 'slot', 'command'))) {
  191. throw new \InvalidArgumentException("Invalid selector type: `$selector`");
  192. }
  193. if (!method_exists($this->connection, $method = "getConnectionBy$selector")) {
  194. $class = get_class($this->connection);
  195. throw new \InvalidArgumentException("Selecting connection by $selector is not supported by $class");
  196. }
  197. if (!$connection = $this->connection->$method($value)) {
  198. throw new \InvalidArgumentException("Cannot find a connection by $selector matching `$value`");
  199. }
  200. $client = new static($connection, $this->getOptions());
  201. if ($callable) {
  202. return call_user_func($callable, $client);
  203. } else {
  204. return $client;
  205. }
  206. }
  207. /**
  208. * Opens the underlying connection and connects to the server.
  209. */
  210. public function connect()
  211. {
  212. $this->connection->connect();
  213. }
  214. /**
  215. * Closes the underlying connection and disconnects from the server.
  216. */
  217. public function disconnect()
  218. {
  219. $this->connection->disconnect();
  220. }
  221. /**
  222. * Closes the underlying connection and disconnects from the server.
  223. *
  224. * This is the same as `Client::disconnect()` as it does not actually send
  225. * the `QUIT` command to Redis, but simply closes the connection.
  226. */
  227. public function quit()
  228. {
  229. $this->disconnect();
  230. }
  231. /**
  232. * Returns the current state of the underlying connection.
  233. *
  234. * @return bool
  235. */
  236. public function isConnected()
  237. {
  238. return $this->connection->isConnected();
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function getConnection()
  244. {
  245. return $this->connection;
  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 possible to identify 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. $response = $this->executeCommand($command->getEvalCommand());
  319. if (!$response instanceof ResponseInterface) {
  320. $response = $command->parseResponse($response);
  321. }
  322. return $response;
  323. }
  324. if ($this->options->exceptions) {
  325. throw new ServerException($response->getMessage());
  326. }
  327. return $response;
  328. }
  329. /**
  330. * Executes the specified initializer method on `$this` by adjusting the
  331. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  332. * simply an utility method to create Redis contexts instances since they
  333. * follow a common initialization path.
  334. *
  335. * @param string $initializer Method name.
  336. * @param array $argv Arguments for the method.
  337. *
  338. * @return mixed
  339. */
  340. private function sharedContextFactory($initializer, $argv = null)
  341. {
  342. switch (count($argv)) {
  343. case 0:
  344. return $this->$initializer();
  345. case 1:
  346. return is_array($argv[0])
  347. ? $this->$initializer($argv[0])
  348. : $this->$initializer(null, $argv[0]);
  349. case 2:
  350. list($arg0, $arg1) = $argv;
  351. return $this->$initializer($arg0, $arg1);
  352. // @codeCoverageIgnoreStart
  353. default:
  354. return $this->$initializer($this, $argv);
  355. }
  356. // @codeCoverageIgnoreEnd
  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 publish/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. }