Client.php 15 KB

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