Client.php 15 KB

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