Client.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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\ScriptedCommand;
  15. use Predis\Configuration\Options;
  16. use Predis\Configuration\OptionsInterface;
  17. use Predis\Connection\AggregatedConnectionInterface;
  18. use Predis\Connection\ConnectionInterface;
  19. use Predis\Connection\ConnectionParametersInterface;
  20. use Predis\Monitor;
  21. use Predis\Pipeline;
  22. use Predis\PubSub;
  23. use Predis\Response;
  24. use Predis\Transaction;
  25. /**
  26. * Client class used for connecting and executing commands on Redis.
  27. *
  28. * This is the main high-level abstraction of Predis upon which various other
  29. * abstractions are built. Internally it aggregates various other classes each
  30. * one with its own responsibility and scope.
  31. *
  32. * @author Daniele Alessandri <suppakilla@gmail.com>
  33. */
  34. class Client implements ClientInterface
  35. {
  36. const VERSION = '0.9.0-dev';
  37. protected $connection;
  38. protected $options;
  39. private $profile;
  40. /**
  41. * @param mixed $parameters Connection parameters for one or more servers.
  42. * @param mixed $options Options to configure some behaviours of the client.
  43. */
  44. public function __construct($parameters = null, $options = null)
  45. {
  46. $this->options = $this->createOptions($options ?: array());
  47. $this->connection = $this->createConnection($parameters ?: array());
  48. $this->profile = $this->options->profile;
  49. }
  50. /**
  51. * Creates a new instance of Predis\Configuration\Options from different
  52. * types of arguments or simply returns the passed argument if it is an
  53. * instance of Predis\Configuration\OptionsInterface.
  54. *
  55. * @param mixed $options Client options.
  56. * @return OptionsInterface
  57. */
  58. protected function createOptions($options)
  59. {
  60. if (is_array($options)) {
  61. return new Options($options);
  62. }
  63. if ($options instanceof OptionsInterface) {
  64. return $options;
  65. }
  66. throw new InvalidArgumentException("Invalid type for client options");
  67. }
  68. /**
  69. * Creates single or aggregate connections from different types of arguments
  70. * (string, array) or returns the passed argument if it is an instance of a
  71. * class implementing Predis\Connection\ConnectionInterface.
  72. *
  73. * Accepted types for connection parameters are:
  74. *
  75. * - Instance of Predis\Connection\ConnectionInterface.
  76. * - Instance of Predis\Connection\ConnectionParametersInterface.
  77. * - Array
  78. * - String
  79. * - Callable
  80. *
  81. * @param mixed $parameters Connection parameters or connection instance.
  82. * @return ConnectionInterface
  83. */
  84. protected function createConnection($parameters)
  85. {
  86. if ($parameters instanceof ConnectionInterface) {
  87. return $parameters;
  88. }
  89. if ($parameters instanceof ConnectionParametersInterface || is_string($parameters)) {
  90. return $this->options->connections->create($parameters);
  91. }
  92. if (is_array($parameters)) {
  93. if (!isset($parameters[0])) {
  94. return $this->options->connections->create($parameters);
  95. }
  96. $options = $this->options;
  97. if ($options->defined('aggregate')) {
  98. $initializer = $this->getConnectionInitializerWrapper($options->aggregate);
  99. $connection = $initializer($parameters, $options);
  100. } else {
  101. if ($options->defined('replication') && $replication = $options->replication) {
  102. $connection = $replication;
  103. } else {
  104. $connection = $options->cluster;
  105. }
  106. $options->connections->aggregate($connection, $parameters);
  107. }
  108. return $connection;
  109. }
  110. if (is_callable($parameters)) {
  111. $initializer = $this->getConnectionInitializerWrapper($parameters);
  112. $connection = $initializer($this->options);
  113. return $connection;
  114. }
  115. throw new InvalidArgumentException('Invalid type for connection parameters');
  116. }
  117. /**
  118. * Wraps a callable to make sure that its returned value represents a valid
  119. * connection type.
  120. *
  121. * @param mixed $callable
  122. * @return mixed
  123. */
  124. protected function getConnectionInitializerWrapper($callable)
  125. {
  126. return function () use ($callable) {
  127. $connection = call_user_func_array($callable, func_get_args());
  128. if (!$connection instanceof ConnectionInterface) {
  129. throw new UnexpectedValueException('The callable connection initializer returned an invalid type');
  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 AggregatedConnectionInterface) {
  212. throw new NotSupportedException(
  213. 'Retrieving connections by ID is supported only when using aggregated connections'
  214. );
  215. }
  216. return $this->connection->getConnectionById($connectionID);
  217. }
  218. /**
  219. * Creates a Redis command with the specified arguments and sends a request
  220. * to the server.
  221. *
  222. * @param string $commandID Command ID.
  223. * @param array $arguments Arguments for the command.
  224. * @return mixed
  225. */
  226. public function __call($commandID, $arguments)
  227. {
  228. $command = $this->createCommand($commandID, $arguments);
  229. $response = $this->executeCommand($command);
  230. return $response;
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. public function createCommand($commandID, $arguments = array())
  236. {
  237. return $this->profile->createCommand($commandID, $arguments);
  238. }
  239. /**
  240. * {@inheritdoc}
  241. */
  242. public function executeCommand(CommandInterface $command)
  243. {
  244. $response = $this->connection->executeCommand($command);
  245. if ($response instanceof Response\ObjectInterface) {
  246. if ($response instanceof Response\ErrorInterface) {
  247. $response = $this->onResponseError($command, $response);
  248. }
  249. return $response;
  250. }
  251. return $command->parseResponse($response);
  252. }
  253. /**
  254. * Handles -ERR responses returned by Redis.
  255. *
  256. * @param CommandInterface $command Redis command that generated the error.
  257. * @param Response\ErrorInterface $response Instance of the error response.
  258. * @return mixed
  259. */
  260. protected function onResponseError(CommandInterface $command, Response\ErrorInterface $response)
  261. {
  262. if ($command instanceof ScriptedCommand && $response->getErrorType() === 'NOSCRIPT') {
  263. $eval = $this->createCommand('eval');
  264. $eval->setRawArguments($command->getEvalArguments());
  265. $response = $this->executeCommand($eval);
  266. if (!$response instanceof Response\ObjectInterface) {
  267. $response = $command->parseResponse($response);
  268. }
  269. return $response;
  270. }
  271. if ($this->options->exceptions) {
  272. throw new Response\ServerException($response->getMessage());
  273. }
  274. return $response;
  275. }
  276. /**
  277. * Executes the specified initializer method on `$this` by adjusting the
  278. * actual invokation depending on the arity (0, 1 or 2 arguments). This is
  279. * simply an utility method to create Redis contexts instances since they
  280. * follow a common initialization path.
  281. *
  282. * @param string $initializer Method name.
  283. * @param array $argv Arguments for the method.
  284. * @return mixed
  285. */
  286. private function sharedContextFactory($initializer, $argv = null)
  287. {
  288. switch (count($argv)) {
  289. case 0:
  290. return $this->$initializer();
  291. case 1:
  292. list($arg0) = $argv;
  293. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  294. case 2:
  295. list($arg0, $arg1) = $argv;
  296. return $this->$initializer($arg0, $arg1);
  297. default:
  298. return $this->$initializer($this, $argv);
  299. }
  300. }
  301. /**
  302. * Creates a new pipeline context and returns it, or returns the results of
  303. * a pipeline executed inside the optionally provided callable object.
  304. *
  305. * @param mixed $arg,... Options for the context, or a callable, or both.
  306. * @return Pipeline\Pipeline|array
  307. */
  308. public function pipeline(/* arguments */)
  309. {
  310. return $this->sharedContextFactory('createPipeline', func_get_args());
  311. }
  312. /**
  313. * Actual pipeline context initializer method.
  314. *
  315. * @param array $options Options for the context.
  316. * @param mixed $callable Optional callable used to execute the context.
  317. * @return Pipeline\Pipeline|array
  318. */
  319. protected function createPipeline(array $options = null, $callable = null)
  320. {
  321. if (isset($options['atomic']) && $options['atomic']) {
  322. $class = 'Predis\Pipeline\Atomic';
  323. } else if (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
  324. $class = 'Predis\Pipeline\FireAndForget';
  325. } else {
  326. $class = 'Predis\Pipeline\Pipeline';
  327. }
  328. $pipeline = new $class($this);
  329. if (isset($callable)) {
  330. return $pipeline->execute($callable);
  331. }
  332. return $pipeline;
  333. }
  334. /**
  335. * Creates a new transaction context and returns it, or returns the results
  336. * of a transaction executed inside the optionally provided callable object.
  337. *
  338. * @param mixed $arg,... Options for the context, or a callable, or both.
  339. * @return Transaction\MultiExec|array
  340. */
  341. public function transaction(/* arguments */)
  342. {
  343. return $this->sharedContextFactory('createTransaction', func_get_args());
  344. }
  345. /**
  346. * Actual transaction context initializer method.
  347. *
  348. * @param array $options Options for the context.
  349. * @param mixed $callable Optional callable used to execute the context.
  350. * @return Transaction\MultiExec|array
  351. */
  352. protected function createTransaction(array $options = null, $callable = null)
  353. {
  354. $transaction = new Transaction\MultiExec($this, $options);
  355. if (isset($callable)) {
  356. return $transaction->execute($callable);
  357. }
  358. return $transaction;
  359. }
  360. /**
  361. * Creates a new publis/subscribe context and returns it, or starts its loop
  362. * inside the optionally provided callable object.
  363. *
  364. * @param mixed $arg,... Options for the context, or a callable, or both.
  365. * @return PubSub\Consumer|NULL
  366. */
  367. public function pubSubLoop(/* arguments */)
  368. {
  369. return $this->sharedContextFactory('createPubSub', func_get_args());
  370. }
  371. /**
  372. * Actual publish/subscribe 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 PubSub\Consumer|NULL
  377. */
  378. protected function createPubSub(array $options = null, $callable = null)
  379. {
  380. $pubsub = new PubSub\Consumer($this, $options);
  381. if (!isset($callable)) {
  382. return $pubsub;
  383. }
  384. foreach ($pubsub as $message) {
  385. if (call_user_func($callable, $pubsub, $message) === false) {
  386. $pubsub->stop();
  387. }
  388. }
  389. }
  390. /**
  391. * Creates a new monitor consumer and returns it.
  392. *
  393. * @return Monitor\Consumer
  394. */
  395. public function monitor()
  396. {
  397. return new Monitor\Consumer($this);
  398. }
  399. }