Client.php 14 KB

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