Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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\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 Configuration\Options($options);
  62. }
  63. if ($options instanceof Configuration\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. * 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 raw(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. list($arg0) = $argv;
  318. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  319. case 2:
  320. list($arg0, $arg1) = $argv;
  321. return $this->$initializer($arg0, $arg1);
  322. default:
  323. return $this->$initializer($this, $argv);
  324. }
  325. }
  326. /**
  327. * Creates a new pipeline context and returns it, or returns the results of
  328. * a pipeline executed inside the optionally provided callable object.
  329. *
  330. * @param mixed $arg,... Options for the context, or a callable, or both.
  331. * @return Pipeline\Pipeline|array
  332. */
  333. public function pipeline(/* arguments */)
  334. {
  335. return $this->sharedContextFactory('createPipeline', func_get_args());
  336. }
  337. /**
  338. * Actual pipeline context initializer method.
  339. *
  340. * @param array $options Options for the context.
  341. * @param mixed $callable Optional callable used to execute the context.
  342. * @return Pipeline\Pipeline|array
  343. */
  344. protected function createPipeline(array $options = null, $callable = null)
  345. {
  346. if (isset($options['atomic']) && $options['atomic']) {
  347. $class = 'Predis\Pipeline\Atomic';
  348. } else if (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
  349. $class = 'Predis\Pipeline\FireAndForget';
  350. } else {
  351. $class = 'Predis\Pipeline\Pipeline';
  352. }
  353. $pipeline = new $class($this);
  354. if (isset($callable)) {
  355. return $pipeline->execute($callable);
  356. }
  357. return $pipeline;
  358. }
  359. /**
  360. * Creates a new transaction context and returns it, or returns the results
  361. * of a transaction executed inside the optionally provided callable object.
  362. *
  363. * @param mixed $arg,... Options for the context, or a callable, or both.
  364. * @return Transaction\MultiExec|array
  365. */
  366. public function transaction(/* arguments */)
  367. {
  368. return $this->sharedContextFactory('createTransaction', func_get_args());
  369. }
  370. /**
  371. * Actual transaction 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 Transaction\MultiExec|array
  376. */
  377. protected function createTransaction(array $options = null, $callable = null)
  378. {
  379. $transaction = new Transaction\MultiExec($this, $options);
  380. if (isset($callable)) {
  381. return $transaction->execute($callable);
  382. }
  383. return $transaction;
  384. }
  385. /**
  386. * Creates a new publis/subscribe context and returns it, or starts its loop
  387. * inside the optionally provided callable object.
  388. *
  389. * @param mixed $arg,... Options for the context, or a callable, or both.
  390. * @return PubSub\Consumer|NULL
  391. */
  392. public function pubSubLoop(/* arguments */)
  393. {
  394. return $this->sharedContextFactory('createPubSub', func_get_args());
  395. }
  396. /**
  397. * Actual publish/subscribe context initializer method.
  398. *
  399. * @param array $options Options for the context.
  400. * @param mixed $callable Optional callable used to execute the context.
  401. * @return PubSub\Consumer|NULL
  402. */
  403. protected function createPubSub(array $options = null, $callable = null)
  404. {
  405. $pubsub = new PubSub\Consumer($this, $options);
  406. if (!isset($callable)) {
  407. return $pubsub;
  408. }
  409. foreach ($pubsub as $message) {
  410. if (call_user_func($callable, $pubsub, $message) === false) {
  411. $pubsub->stop();
  412. }
  413. }
  414. }
  415. /**
  416. * Creates a new monitor consumer and returns it.
  417. *
  418. * @return Monitor\Consumer
  419. */
  420. public function monitor()
  421. {
  422. return new Monitor\Consumer($this);
  423. }
  424. }