Client.php 13 KB

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