Client.php 14 KB

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