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\CommandInterface;
  14. use Predis\Command\RawCommand;
  15. use Predis\Command\ScriptCommand;
  16. use Predis\Configuration;
  17. use Predis\Connection;
  18. use Predis\Monitor;
  19. use Predis\Pipeline;
  20. use Predis\PubSub;
  21. use Predis\Response;
  22. use Predis\Transaction;
  23. /**
  24. * Client class used for connecting and executing commands on Redis.
  25. *
  26. * This is the main high-level abstraction of Predis upon which various other
  27. * abstractions are built. Internally it aggregates various other classes each
  28. * one with its own responsibility and scope.
  29. *
  30. * @author Daniele Alessandri <suppakilla@gmail.com>
  31. */
  32. class Client implements ClientInterface
  33. {
  34. const VERSION = '0.9.0-dev';
  35. protected $connection;
  36. protected $options;
  37. private $profile;
  38. /**
  39. * @param mixed $parameters Connection parameters for one or more servers.
  40. * @param mixed $options Options to configure some behaviours of the client.
  41. */
  42. public function __construct($parameters = null, $options = null)
  43. {
  44. $this->options = $this->createOptions($options ?: array());
  45. $this->connection = $this->createConnection($parameters ?: array());
  46. $this->profile = $this->options->profile;
  47. }
  48. /**
  49. * Creates a new instance of Predis\Configuration\Options from different
  50. * types of arguments or simply returns the passed argument if it is an
  51. * instance of Predis\Configuration\OptionsInterface.
  52. *
  53. * @param mixed $options Client options.
  54. * @return OptionsInterface
  55. */
  56. protected function createOptions($options)
  57. {
  58. if (is_array($options)) {
  59. return new Configuration\Options($options);
  60. }
  61. if ($options instanceof Configuration\OptionsInterface) {
  62. return $options;
  63. }
  64. throw new InvalidArgumentException("Invalid type for client options");
  65. }
  66. /**
  67. * Creates single or aggregate connections from different types of arguments
  68. * (string, array) or returns the passed argument if it is an instance of a
  69. * class implementing Predis\Connection\ConnectionInterface.
  70. *
  71. * Accepted types for connection parameters are:
  72. *
  73. * - Instance of Predis\Connection\ConnectionInterface.
  74. * - Instance of Predis\Connection\ParametersInterface.
  75. * - Array
  76. * - String
  77. * - Callable
  78. *
  79. * @param mixed $parameters Connection parameters or connection instance.
  80. * @return Connection\ConnectionInterface
  81. */
  82. protected function createConnection($parameters)
  83. {
  84. if ($parameters instanceof Connection\ConnectionInterface) {
  85. return $parameters;
  86. }
  87. if ($parameters instanceof Connection\ParametersInterface || is_string($parameters)) {
  88. return $this->options->connections->create($parameters);
  89. }
  90. if (is_array($parameters)) {
  91. if (!isset($parameters[0])) {
  92. return $this->options->connections->create($parameters);
  93. }
  94. $options = $this->options;
  95. if ($options->defined('aggregate')) {
  96. $initializer = $this->getConnectionInitializerWrapper($options->aggregate);
  97. $connection = $initializer($parameters, $options);
  98. } else {
  99. if ($options->defined('replication') && $replication = $options->replication) {
  100. $connection = $replication;
  101. } else {
  102. $connection = $options->cluster;
  103. }
  104. $options->connections->aggregate($connection, $parameters);
  105. }
  106. return $connection;
  107. }
  108. if (is_callable($parameters)) {
  109. $initializer = $this->getConnectionInitializerWrapper($parameters);
  110. $connection = $initializer($this->options);
  111. return $connection;
  112. }
  113. throw new InvalidArgumentException('Invalid type for connection parameters');
  114. }
  115. /**
  116. * Wraps a callable to make sure that its returned value represents a valid
  117. * connection type.
  118. *
  119. * @param mixed $callable
  120. * @return mixed
  121. */
  122. protected function getConnectionInitializerWrapper($callable)
  123. {
  124. return function () use ($callable) {
  125. $connection = call_user_func_array($callable, func_get_args());
  126. if (!$connection instanceof Connection\ConnectionInterface) {
  127. throw new UnexpectedValueException(
  128. 'The callable connection initializer returned an invalid type'
  129. );
  130. }
  131. return $connection;
  132. };
  133. }
  134. /**
  135. * {@inheritdoc}
  136. */
  137. public function getProfile()
  138. {
  139. return $this->profile;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function getOptions()
  145. {
  146. return $this->options;
  147. }
  148. /**
  149. * Creates a new client instance for the specified connection ID or alias,
  150. * only when working with an aggregate connection (cluster, replication).
  151. * The new client instances uses the same options of the original one.
  152. *
  153. * @return Client
  154. */
  155. public function getClientFor($connectionID)
  156. {
  157. if (!$connection = $this->getConnectionById($connectionID)) {
  158. throw new InvalidArgumentException("Invalid connection ID: $connectionID");
  159. }
  160. return new static($connection, $this->options);
  161. }
  162. /**
  163. * Opens the underlying connection and connects to the server.
  164. */
  165. public function connect()
  166. {
  167. $this->connection->connect();
  168. }
  169. /**
  170. * Closes the underlying connection and disconnects from the server.
  171. */
  172. public function disconnect()
  173. {
  174. $this->connection->disconnect();
  175. }
  176. /**
  177. * Closes the underlying connection and disconnects from the server.
  178. *
  179. * This is the same as `Client::disconnect()` as it does not actually send
  180. * the `QUIT` command to Redis, but simply closes the connection.
  181. */
  182. public function quit()
  183. {
  184. $this->disconnect();
  185. }
  186. /**
  187. * Returns the current state of the underlying connection.
  188. *
  189. * @return bool
  190. */
  191. public function isConnected()
  192. {
  193. return $this->connection->isConnected();
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function getConnection()
  199. {
  200. return $this->connection;
  201. }
  202. /**
  203. * Retrieves the specified connection from the aggregate connection when the
  204. * client is in cluster or replication mode.
  205. *
  206. * @param string $connectionID Index or alias of the single connection.
  207. * @return Connection\SingleConnectionInterface
  208. */
  209. public function getConnectionById($connectionID)
  210. {
  211. if (!$this->connection instanceof Connection\AggregateConnectionInterface) {
  212. throw new NotSupportedException(
  213. 'Retrieving connections by ID is supported only when using aggregate connections'
  214. );
  215. }
  216. return $this->connection->getConnectionById($connectionID);
  217. }
  218. /**
  219. * Executes a command without filtering its arguments, parsing the response,
  220. * applying any prefix to keys or throwing exceptions on Redis errors even
  221. * regardless of client options.
  222. *
  223. * It is possibile to indentify Redis error responses from normal responses
  224. * using the second optional argument which is populated by reference.
  225. *
  226. * @param array $arguments Command arguments as defined by the command signature.
  227. * @param bool $error Set to TRUE when Redis returned an error response.
  228. * @return mixed
  229. */
  230. public function executeRaw(array $arguments, &$error = null)
  231. {
  232. $error = false;
  233. $command = new RawCommand($arguments);
  234. $response = $this->connection->executeCommand($command);
  235. if ($response instanceof Response\ResponseInterface) {
  236. if ($response instanceof Response\ErrorInterface) {
  237. $error = true;
  238. }
  239. return (string) $response;
  240. }
  241. return $response;
  242. }
  243. /**
  244. * Creates a Redis command with the specified arguments and sends a request
  245. * to the server.
  246. *
  247. * @param string $commandID Command ID.
  248. * @param array $arguments Arguments for the command.
  249. * @return mixed
  250. */
  251. public function __call($commandID, $arguments)
  252. {
  253. $command = $this->createCommand($commandID, $arguments);
  254. $response = $this->executeCommand($command);
  255. return $response;
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function createCommand($commandID, $arguments = array())
  261. {
  262. return $this->profile->createCommand($commandID, $arguments);
  263. }
  264. /**
  265. * {@inheritdoc}
  266. */
  267. public function executeCommand(CommandInterface $command)
  268. {
  269. $response = $this->connection->executeCommand($command);
  270. if ($response instanceof Response\ResponseInterface) {
  271. if ($response instanceof Response\ErrorInterface) {
  272. $response = $this->onResponseError($command, $response);
  273. }
  274. return $response;
  275. }
  276. return $command->parseResponse($response);
  277. }
  278. /**
  279. * Handles -ERR responses returned by Redis.
  280. *
  281. * @param CommandInterface $command Redis command that generated the error.
  282. * @param Response\ErrorInterface $response Instance of the error response.
  283. * @return mixed
  284. */
  285. protected function onResponseError(CommandInterface $command, Response\ErrorInterface $response)
  286. {
  287. if ($command instanceof 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. }