Predis.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class MalformedServerResponse extends ServerException { }
  7. /* ------------------------------------------------------------------------- */
  8. class Client {
  9. // TODO: command arguments should be sanitized or checked for bad arguments
  10. // (e.g. CRLF in keys for inline commands)
  11. private $_connection, $_serverProfile;
  12. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  13. $this->setProfile(
  14. $serverProfile === null
  15. ? RedisServerProfile::getDefault()
  16. : $serverProfile
  17. );
  18. $this->setupConnection($parameters);
  19. }
  20. public function __destruct() {
  21. $this->_connection->disconnect();
  22. }
  23. public static function create(/* arguments */) {
  24. $argv = func_get_args();
  25. $argc = func_num_args();
  26. $serverProfile = null;
  27. $lastArg = $argv[$argc-1];
  28. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  29. $serverProfile = array_pop($argv);
  30. $argc--;
  31. }
  32. if ($argc === 0) {
  33. throw new ClientException('Missing connection parameters');
  34. }
  35. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  36. }
  37. private function setupConnection($parameters) {
  38. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  39. throw new ClientException('Invalid parameters type (array or string expected)');
  40. }
  41. if (is_array($parameters) && isset($parameters[0])) {
  42. $cluster = new ConnectionCluster();
  43. foreach ($parameters as $shardParams) {
  44. $cluster->add($this->createConnection($shardParams));
  45. }
  46. $this->setConnection($cluster);
  47. }
  48. else {
  49. $this->setConnection($this->createConnection($parameters));
  50. }
  51. }
  52. private function createConnection($parameters) {
  53. $params = new ConnectionParameters($parameters);
  54. $connection = new Connection($params);
  55. if ($params->password !== null) {
  56. $connection->pushInitCommand($this->createCommand(
  57. 'auth', array($params->password)
  58. ));
  59. }
  60. if ($params->database !== null) {
  61. $connection->pushInitCommand($this->createCommand(
  62. 'select', array($params->database)
  63. ));
  64. }
  65. return $connection;
  66. }
  67. private function setConnection(IConnection $connection) {
  68. $this->_connection = $connection;
  69. }
  70. public function setProfile(RedisServerProfile $serverProfile) {
  71. $this->_serverProfile = $serverProfile;
  72. }
  73. public function getProfile() {
  74. return $this->_serverProfile;
  75. }
  76. public function connect() {
  77. $this->_connection->connect();
  78. }
  79. public function disconnect() {
  80. $this->_connection->disconnect();
  81. }
  82. public function isConnected() {
  83. return $this->_connection->isConnected();
  84. }
  85. public function getConnection() {
  86. return $this->_connection;
  87. }
  88. public function __call($method, $arguments) {
  89. $command = $this->_serverProfile->createCommand($method, $arguments);
  90. return $this->executeCommand($command);
  91. }
  92. public function createCommand($method, $arguments = array()) {
  93. return $this->_serverProfile->createCommand($method, $arguments);
  94. }
  95. private function executeCommandInternal(IConnection $connection, Command $command) {
  96. $connection->writeCommand($command);
  97. if ($command->closesConnection()) {
  98. return $connection->disconnect();
  99. }
  100. return $connection->readResponse($command);
  101. }
  102. public function executeCommand(Command $command) {
  103. return self::executeCommandInternal($this->_connection, $command);
  104. }
  105. public function executeCommandOnShards(Command $command) {
  106. $replies = array();
  107. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  108. foreach($this->_connection as $connection) {
  109. $replies[] = self::executeCommandInternal($connection, $command);
  110. }
  111. }
  112. else {
  113. $replies[] = self::executeCommandInternal($this->_connection, $command);
  114. }
  115. return $replies;
  116. }
  117. public function rawCommand($rawCommandData, $closesConnection = false) {
  118. // TODO: rather than check the type of a connection instance, we should
  119. // check if it does respond to the rawCommand method.
  120. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  121. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  122. }
  123. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  124. }
  125. public function pipeline(\Closure $pipelineBlock = null) {
  126. $pipeline = new CommandPipeline($this);
  127. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  128. }
  129. public function multiExec(\Closure $multiExecBlock = null) {
  130. $multiExec = new MultiExecBlock($this);
  131. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  132. }
  133. public function registerCommands(Array $commands) {
  134. $this->_serverProfile->registerCommands($commands);
  135. }
  136. public function registerCommand($command, $aliases) {
  137. $this->_serverProfile->registerCommand($command, $aliases);
  138. }
  139. }
  140. /* ------------------------------------------------------------------------- */
  141. abstract class Command {
  142. private $_arguments, $_hash;
  143. public abstract function getCommandId();
  144. public abstract function serializeRequest($command, $arguments);
  145. public function canBeHashed() {
  146. return true;
  147. }
  148. public function getHash() {
  149. if (isset($this->_hash)) {
  150. return $this->_hash;
  151. }
  152. else {
  153. if (isset($this->_arguments[0])) {
  154. $key = $this->_arguments[0];
  155. $start = strpos($key, '{');
  156. $end = strpos($key, '}');
  157. if ($start !== false && $end !== false) {
  158. $key = substr($key, ++$start, $end - $start);
  159. }
  160. $this->_hash = crc32($key);
  161. return $this->_hash;
  162. }
  163. }
  164. return null;
  165. }
  166. public function closesConnection() {
  167. return false;
  168. }
  169. protected function filterArguments(Array $arguments) {
  170. return $arguments;
  171. }
  172. public function setArguments(/* arguments */) {
  173. $this->_arguments = $this->filterArguments(func_get_args());
  174. }
  175. public function setArgumentsArray(Array $arguments) {
  176. $this->_arguments = $this->filterArguments($arguments);
  177. }
  178. protected function getArguments() {
  179. return isset($this->_arguments) ? $this->_arguments : array();
  180. }
  181. public function getArgument($index = 0) {
  182. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  183. }
  184. public function parseResponse($data) {
  185. return $data;
  186. }
  187. public final function __invoke() {
  188. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  189. }
  190. }
  191. abstract class InlineCommand extends Command {
  192. public function serializeRequest($command, $arguments) {
  193. if (isset($arguments[0]) && is_array($arguments[0])) {
  194. $arguments[0] = implode($arguments[0], ' ');
  195. }
  196. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  197. }
  198. }
  199. abstract class BulkCommand extends Command {
  200. public function serializeRequest($command, $arguments) {
  201. $data = array_pop($arguments);
  202. if (is_array($data)) {
  203. $data = implode($data, ' ');
  204. }
  205. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  206. Response::NEWLINE . $data . Response::NEWLINE;
  207. }
  208. }
  209. abstract class MultiBulkCommand extends Command {
  210. public function serializeRequest($command, $arguments) {
  211. $buffer = array();
  212. $cmd_args = null;
  213. if (count($arguments) === 1 && is_array($arguments[0])) {
  214. $cmd_args = array();
  215. foreach ($arguments[0] as $k => $v) {
  216. $cmd_args[] = $k;
  217. $cmd_args[] = $v;
  218. }
  219. }
  220. else {
  221. $cmd_args = $arguments;
  222. }
  223. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  224. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  225. foreach ($cmd_args as $argument) {
  226. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  227. }
  228. return implode('', $buffer);
  229. }
  230. }
  231. /* ------------------------------------------------------------------------- */
  232. class Response {
  233. const NEWLINE = "\r\n";
  234. const OK = 'OK';
  235. const ERROR = 'ERR';
  236. const QUEUED = 'QUEUED';
  237. const NULL = 'nil';
  238. private static $_prefixHandlers;
  239. private static function initializePrefixHandlers() {
  240. return array(
  241. // status
  242. '+' => function($socket) {
  243. $status = rtrim(fgets($socket), Response::NEWLINE);
  244. if ($status === Response::OK) {
  245. return true;
  246. }
  247. else if ($status === Response::QUEUED) {
  248. return new ResponseQueued();
  249. }
  250. return $status;
  251. },
  252. // error
  253. '-' => function($socket) {
  254. $errorMessage = rtrim(fgets($socket), Response::NEWLINE);
  255. throw new ServerException(substr($errorMessage, 4));
  256. },
  257. // bulk
  258. '$' => function($socket) {
  259. $dataLength = rtrim(fgets($socket), Response::NEWLINE);
  260. if (!is_numeric($dataLength)) {
  261. throw new ClientException("Cannot parse '$dataLength' as data length");
  262. }
  263. if ($dataLength > 0) {
  264. $value = stream_get_contents($socket, $dataLength);
  265. fread($socket, 2);
  266. return $value;
  267. }
  268. else if ($dataLength == 0) {
  269. fread($socket, 2);
  270. return '';
  271. }
  272. return null;
  273. },
  274. // multibulk
  275. '*' => function($socket) {
  276. $rawLength = rtrim(fgets($socket), Response::NEWLINE);
  277. if (!is_numeric($rawLength)) {
  278. throw new ClientException("Cannot parse '$rawLength' as data length");
  279. }
  280. $listLength = (int) $rawLength;
  281. if ($listLength === -1) {
  282. return null;
  283. }
  284. $list = array();
  285. if ($listLength > 0) {
  286. for ($i = 0; $i < $listLength; $i++) {
  287. $handler = Response::getPrefixHandler(fgetc($socket));
  288. $list[] = $handler($socket);
  289. }
  290. }
  291. return $list;
  292. },
  293. // integer
  294. ':' => function($socket) {
  295. $number = rtrim(fgets($socket), Response::NEWLINE);
  296. if (is_numeric($number)) {
  297. return (int) $number;
  298. }
  299. else {
  300. if ($number !== Response::NULL) {
  301. throw new ClientException("Cannot parse '$number' as numeric response");
  302. }
  303. return null;
  304. }
  305. }
  306. );
  307. }
  308. public static function getPrefixHandler($prefix) {
  309. if (self::$_prefixHandlers === null) {
  310. self::$_prefixHandlers = self::initializePrefixHandlers();
  311. }
  312. $handler = self::$_prefixHandlers[$prefix];
  313. if ($handler === null) {
  314. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  315. }
  316. return $handler;
  317. }
  318. }
  319. class ResponseQueued {
  320. public $queued = true;
  321. public function __toString() {
  322. return Response::QUEUED;
  323. }
  324. }
  325. class CommandPipeline {
  326. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  327. public function __construct(Client $redisClient) {
  328. $this->_redisClient = $redisClient;
  329. $this->_pipelineBuffer = array();
  330. $this->_returnValues = array();
  331. }
  332. public function __call($method, $arguments) {
  333. $command = $this->_redisClient->createCommand($method, $arguments);
  334. $this->recordCommand($command);
  335. }
  336. private function recordCommand(Command $command) {
  337. $this->_pipelineBuffer[] = $command;
  338. }
  339. private function getRecordedCommands() {
  340. return $this->_pipelineBuffer;
  341. }
  342. public function flushPipeline() {
  343. if (count($this->_pipelineBuffer) === 0) {
  344. return;
  345. }
  346. $connection = $this->_redisClient->getConnection();
  347. $commands = $this->getRecordedCommands();
  348. foreach ($commands as $command) {
  349. $connection->writeCommand($command);
  350. }
  351. foreach ($commands as $command) {
  352. $this->_returnValues[] = $connection->readResponse($command);
  353. }
  354. $this->_pipelineBuffer = array();
  355. }
  356. private function setRunning($bool) {
  357. // TODO: I am honest when I say that I don't like this approach.
  358. if ($bool == true && $this->_running == true) {
  359. throw new ClientException("This pipeline is already opened");
  360. }
  361. $this->_running = $bool;
  362. }
  363. public function execute(\Closure $block = null) {
  364. $this->setRunning(true);
  365. $pipelineBlockException = null;
  366. try {
  367. if ($block !== null) {
  368. $block($this);
  369. }
  370. $this->flushPipeline();
  371. }
  372. catch (\Exception $exception) {
  373. $pipelineBlockException = $exception;
  374. }
  375. $this->setRunning(false);
  376. if ($pipelineBlockException !== null) {
  377. throw $pipelineBlockException;
  378. }
  379. return $this->_returnValues;
  380. }
  381. }
  382. class MultiExecBlock {
  383. private $_redisClient, $_commands, $_initialized;
  384. public function __construct(Client $redisClient) {
  385. $this->_initialized = false;
  386. $this->_redisClient = $redisClient;
  387. $this->_commands = array();
  388. }
  389. private function initialize() {
  390. if ($this->_initialized === false) {
  391. $this->_redisClient->multi();
  392. $this->_initialized = true;
  393. }
  394. }
  395. public function __call($method, $arguments) {
  396. $this->initialize();
  397. $command = $this->_redisClient->createCommand($method, $arguments);
  398. $response = $this->_redisClient->executeCommand($command);
  399. if (isset($response->queued)) {
  400. $this->_commands[] = $command;
  401. return $response;
  402. }
  403. else {
  404. throw new ClientException('The server did not respond with a QUEUED status reply');
  405. }
  406. }
  407. public function execute(\Closure $block = null) {
  408. $blockException = null;
  409. $returnValues = array();
  410. try {
  411. if ($block !== null) {
  412. $block($this);
  413. }
  414. $execReply = $this->_redisClient->exec();
  415. for ($i = 0; $i < count($execReply); $i++) {
  416. $returnValues[] = $this->_commands[$i]->parseResponse($execReply[$i]);
  417. }
  418. }
  419. catch (\Exception $exception) {
  420. $blockException = $exception;
  421. }
  422. if ($blockException !== null) {
  423. throw $blockException;
  424. }
  425. return $returnValues;
  426. }
  427. }
  428. /* ------------------------------------------------------------------------- */
  429. class ConnectionParameters {
  430. const DEFAULT_HOST = '127.0.0.1';
  431. const DEFAULT_PORT = 6379;
  432. private $_parameters;
  433. public function __construct($parameters) {
  434. $parameters = $parameters !== null ? $parameters : array();
  435. $this->_parameters = is_array($parameters)
  436. ? self::filterConnectionParams($parameters)
  437. : self::parseURI($parameters);
  438. }
  439. private static function parseURI($uri) {
  440. $parsed = @parse_url($uri);
  441. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  442. throw new ClientException("Invalid URI: $uri");
  443. }
  444. if (array_key_exists('query', $parsed)) {
  445. $details = array();
  446. foreach (explode('&', $parsed['query']) as $kv) {
  447. list($k, $v) = explode('=', $kv);
  448. switch ($k) {
  449. case 'database':
  450. $details['database'] = $v;
  451. break;
  452. case 'password':
  453. $details['password'] = $v;
  454. break;
  455. case 'connection_timeout':
  456. $details['connection_timeout'] = $v;
  457. break;
  458. case 'read_write_timeout':
  459. $details['read_write_timeout'] = $v;
  460. break;
  461. }
  462. }
  463. $parsed = array_merge($parsed, $details);
  464. }
  465. return self::filterConnectionParams($parsed);
  466. }
  467. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  468. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  469. }
  470. private static function filterConnectionParams($parameters) {
  471. return array(
  472. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  473. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  474. 'database' => self::getParamOrDefault($parameters, 'database'),
  475. 'password' => self::getParamOrDefault($parameters, 'password'),
  476. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout'),
  477. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  478. );
  479. }
  480. public function __get($parameter) {
  481. return $this->_parameters[$parameter];
  482. }
  483. public function __isset($parameter) {
  484. return isset($this->_parameters[$parameter]);
  485. }
  486. }
  487. interface IConnection {
  488. public function connect();
  489. public function disconnect();
  490. public function isConnected();
  491. public function writeCommand(Command $command);
  492. public function readResponse(Command $command);
  493. }
  494. class Connection implements IConnection {
  495. const CONNECTION_TIMEOUT = 2;
  496. private $_params, $_socket, $_initCmds;
  497. public function __construct(ConnectionParameters $parameters) {
  498. $this->_params = $parameters;
  499. $this->_initCmds = array();
  500. }
  501. public function __destruct() {
  502. $this->disconnect();
  503. }
  504. public function isConnected() {
  505. return is_resource($this->_socket);
  506. }
  507. public function connect() {
  508. if ($this->isConnected()) {
  509. throw new ClientException('Connection already estabilished');
  510. }
  511. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  512. $connectionTimeout = $this->_params->connection_timeout ?: self::CONNECTION_TIMEOUT;
  513. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $connectionTimeout);
  514. if (!$this->_socket) {
  515. throw new ClientException(trim($errstr), $errno);
  516. }
  517. if (isset($this->_params->read_write_timeout)) {
  518. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  519. }
  520. if (count($this->_initCmds) > 0){
  521. $this->sendInitializationCommands();
  522. }
  523. }
  524. public function disconnect() {
  525. if ($this->isConnected()) {
  526. fclose($this->_socket);
  527. }
  528. }
  529. public function pushInitCommand(Command $command){
  530. $this->_initCmds[] = $command;
  531. }
  532. private function sendInitializationCommands() {
  533. foreach ($this->_initCmds as $command) {
  534. $this->writeCommand($command);
  535. }
  536. foreach ($this->_initCmds as $command) {
  537. $this->readResponse($command);
  538. }
  539. }
  540. public function writeCommand(Command $command) {
  541. fwrite($this->getSocket(), $command());
  542. }
  543. public function readResponse(Command $command) {
  544. $socket = $this->getSocket();
  545. $handler = Response::getPrefixHandler(fgetc($socket));
  546. $response = $handler($socket);
  547. return isset($response->queued) ? $response : $command->parseResponse($response);
  548. }
  549. public function rawCommand($rawCommandData, $closesConnection = false) {
  550. $socket = $this->getSocket();
  551. fwrite($socket, $rawCommandData);
  552. if ($closesConnection) {
  553. return;
  554. }
  555. $handler = Response::getPrefixHandler(fgetc($socket));
  556. return $handler($socket);
  557. }
  558. public function getSocket() {
  559. if (!$this->isConnected()) {
  560. $this->connect();
  561. }
  562. return $this->_socket;
  563. }
  564. public function __toString() {
  565. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  566. }
  567. }
  568. class ConnectionCluster implements IConnection, \IteratorAggregate {
  569. // TODO: find a clean way to handle connection failures of single nodes.
  570. private $_pool, $_ring;
  571. public function __construct() {
  572. $this->_pool = array();
  573. $this->_ring = new Utilities\HashRing();
  574. }
  575. public function __destruct() {
  576. $this->disconnect();
  577. }
  578. public function isConnected() {
  579. foreach ($this->_pool as $connection) {
  580. if ($connection->isConnected()) {
  581. return true;
  582. }
  583. }
  584. return false;
  585. }
  586. public function connect() {
  587. foreach ($this->_pool as $connection) {
  588. $connection->connect();
  589. }
  590. }
  591. public function disconnect() {
  592. foreach ($this->_pool as $connection) {
  593. $connection->disconnect();
  594. }
  595. }
  596. public function add(Connection $connection) {
  597. $this->_pool[] = $connection;
  598. $this->_ring->add($connection);
  599. }
  600. private function getConnection(Command $command) {
  601. if ($command->canBeHashed() === false) {
  602. throw new ClientException(
  603. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  604. );
  605. }
  606. return $this->_ring->get($command->getHash());
  607. }
  608. public function getConnectionById($id = null) {
  609. return $this->_pool[$id === null ? 0 : $id];
  610. }
  611. public function getIterator() {
  612. return new \ArrayIterator($this->_pool);
  613. }
  614. public function writeCommand(Command $command) {
  615. $this->getConnection($command)->writeCommand($command);
  616. }
  617. public function readResponse(Command $command) {
  618. return $this->getConnection($command)->readResponse($command);
  619. }
  620. }
  621. /* ------------------------------------------------------------------------- */
  622. abstract class RedisServerProfile {
  623. const DEFAULT_SERVER_PROFILE = '\Predis\RedisServer__V1_2';
  624. private $_registeredCommands;
  625. public function __construct() {
  626. $this->_registeredCommands = $this->getSupportedCommands();
  627. }
  628. public abstract function getVersion();
  629. protected abstract function getSupportedCommands();
  630. public static function getDefault() {
  631. $defaultProfile = self::DEFAULT_SERVER_PROFILE;
  632. return new $defaultProfile();
  633. }
  634. public function supportsCommand($command) {
  635. return isset($this->_registeredCommands[$command]);
  636. }
  637. public function createCommand($method, $arguments = array()) {
  638. $commandClass = $this->_registeredCommands[$method];
  639. if ($commandClass === null) {
  640. throw new ClientException("'$method' is not a registered Redis command");
  641. }
  642. $command = new $commandClass();
  643. $command->setArgumentsArray($arguments);
  644. return $command;
  645. }
  646. public function registerCommands(Array $commands) {
  647. foreach ($commands as $command => $aliases) {
  648. $this->registerCommand($command, $aliases);
  649. }
  650. }
  651. public function registerCommand($command, $aliases) {
  652. $commandReflection = new \ReflectionClass($command);
  653. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  654. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  655. }
  656. if (is_array($aliases)) {
  657. foreach ($aliases as $alias) {
  658. $this->_registeredCommands[$alias] = $command;
  659. }
  660. }
  661. else {
  662. $this->_registeredCommands[$aliases] = $command;
  663. }
  664. }
  665. }
  666. class RedisServer__V1_0 extends RedisServerProfile {
  667. public function getVersion() { return '1.0'; }
  668. public function getSupportedCommands() {
  669. return array(
  670. /* miscellaneous commands */
  671. 'ping' => '\Predis\Commands\Ping',
  672. 'echo' => '\Predis\Commands\DoEcho',
  673. 'auth' => '\Predis\Commands\Auth',
  674. /* connection handling */
  675. 'quit' => '\Predis\Commands\Quit',
  676. /* commands operating on string values */
  677. 'set' => '\Predis\Commands\Set',
  678. 'setnx' => '\Predis\Commands\SetPreserve',
  679. 'setPreserve' => '\Predis\Commands\SetPreserve',
  680. 'get' => '\Predis\Commands\Get',
  681. 'mget' => '\Predis\Commands\GetMultiple',
  682. 'getMultiple' => '\Predis\Commands\GetMultiple',
  683. 'getset' => '\Predis\Commands\GetSet',
  684. 'getSet' => '\Predis\Commands\GetSet',
  685. 'incr' => '\Predis\Commands\Increment',
  686. 'increment' => '\Predis\Commands\Increment',
  687. 'incrby' => '\Predis\Commands\IncrementBy',
  688. 'incrementBy' => '\Predis\Commands\IncrementBy',
  689. 'decr' => '\Predis\Commands\Decrement',
  690. 'decrement' => '\Predis\Commands\Decrement',
  691. 'decrby' => '\Predis\Commands\DecrementBy',
  692. 'decrementBy' => '\Predis\Commands\DecrementBy',
  693. 'exists' => '\Predis\Commands\Exists',
  694. 'del' => '\Predis\Commands\Delete',
  695. 'delete' => '\Predis\Commands\Delete',
  696. 'type' => '\Predis\Commands\Type',
  697. /* commands operating on the key space */
  698. 'keys' => '\Predis\Commands\Keys',
  699. 'randomkey' => '\Predis\Commands\RandomKey',
  700. 'randomKey' => '\Predis\Commands\RandomKey',
  701. 'rename' => '\Predis\Commands\Rename',
  702. 'renamenx' => '\Predis\Commands\RenamePreserve',
  703. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  704. 'expire' => '\Predis\Commands\Expire',
  705. 'expireat' => '\Predis\Commands\ExpireAt',
  706. 'expireAt' => '\Predis\Commands\ExpireAt',
  707. 'dbsize' => '\Predis\Commands\DatabaseSize',
  708. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  709. 'ttl' => '\Predis\Commands\TimeToLive',
  710. 'timeToLive' => '\Predis\Commands\TimeToLive',
  711. /* commands operating on lists */
  712. 'rpush' => '\Predis\Commands\ListPushTail',
  713. 'pushTail' => '\Predis\Commands\ListPushTail',
  714. 'lpush' => '\Predis\Commands\ListPushHead',
  715. 'pushHead' => '\Predis\Commands\ListPushHead',
  716. 'llen' => '\Predis\Commands\ListLength',
  717. 'listLength' => '\Predis\Commands\ListLength',
  718. 'lrange' => '\Predis\Commands\ListRange',
  719. 'listRange' => '\Predis\Commands\ListRange',
  720. 'ltrim' => '\Predis\Commands\ListTrim',
  721. 'listTrim' => '\Predis\Commands\ListTrim',
  722. 'lindex' => '\Predis\Commands\ListIndex',
  723. 'listIndex' => '\Predis\Commands\ListIndex',
  724. 'lset' => '\Predis\Commands\ListSet',
  725. 'listSet' => '\Predis\Commands\ListSet',
  726. 'lrem' => '\Predis\Commands\ListRemove',
  727. 'listRemove' => '\Predis\Commands\ListRemove',
  728. 'lpop' => '\Predis\Commands\ListPopFirst',
  729. 'popFirst' => '\Predis\Commands\ListPopFirst',
  730. 'rpop' => '\Predis\Commands\ListPopLast',
  731. 'popLast' => '\Predis\Commands\ListPopLast',
  732. /* commands operating on sets */
  733. 'sadd' => '\Predis\Commands\SetAdd',
  734. 'setAdd' => '\Predis\Commands\SetAdd',
  735. 'srem' => '\Predis\Commands\SetRemove',
  736. 'setRemove' => '\Predis\Commands\SetRemove',
  737. 'spop' => '\Predis\Commands\SetPop',
  738. 'setPop' => '\Predis\Commands\SetPop',
  739. 'smove' => '\Predis\Commands\SetMove',
  740. 'setMove' => '\Predis\Commands\SetMove',
  741. 'scard' => '\Predis\Commands\SetCardinality',
  742. 'setCardinality' => '\Predis\Commands\SetCardinality',
  743. 'sismember' => '\Predis\Commands\SetIsMember',
  744. 'setIsMember' => '\Predis\Commands\SetIsMember',
  745. 'sinter' => '\Predis\Commands\SetIntersection',
  746. 'setIntersection' => '\Predis\Commands\SetIntersection',
  747. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  748. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  749. 'sunion' => '\Predis\Commands\SetUnion',
  750. 'setUnion' => '\Predis\Commands\SetUnion',
  751. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  752. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  753. 'sdiff' => '\Predis\Commands\SetDifference',
  754. 'setDifference' => '\Predis\Commands\SetDifference',
  755. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  756. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  757. 'smembers' => '\Predis\Commands\SetMembers',
  758. 'setMembers' => '\Predis\Commands\SetMembers',
  759. 'srandmember' => '\Predis\Commands\SetRandomMember',
  760. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  761. /* multiple databases handling commands */
  762. 'select' => '\Predis\Commands\SelectDatabase',
  763. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  764. 'move' => '\Predis\Commands\MoveKey',
  765. 'moveKey' => '\Predis\Commands\MoveKey',
  766. 'flushdb' => '\Predis\Commands\FlushDatabase',
  767. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  768. 'flushall' => '\Predis\Commands\FlushAll',
  769. 'flushDatabases' => '\Predis\Commands\FlushAll',
  770. /* sorting */
  771. 'sort' => '\Predis\Commands\Sort',
  772. /* remote server control commands */
  773. 'info' => '\Predis\Commands\Info',
  774. 'slaveof' => '\Predis\Commands\SlaveOf',
  775. 'slaveOf' => '\Predis\Commands\SlaveOf',
  776. /* persistence control commands */
  777. 'save' => '\Predis\Commands\Save',
  778. 'bgsave' => '\Predis\Commands\BackgroundSave',
  779. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  780. 'lastsave' => '\Predis\Commands\LastSave',
  781. 'lastSave' => '\Predis\Commands\LastSave',
  782. 'shutdown' => '\Predis\Commands\Shutdown'
  783. );
  784. }
  785. }
  786. class RedisServer__V1_2 extends RedisServer__V1_0 {
  787. public function getVersion() { return '1.2'; }
  788. public function getSupportedCommands() {
  789. return array_merge(parent::getSupportedCommands(), array(
  790. /* commands operating on string values */
  791. 'mset' => '\Predis\Commands\SetMultiple',
  792. 'setMultiple' => '\Predis\Commands\SetMultiple',
  793. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  794. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  795. /* commands operating on lists */
  796. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  797. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  798. /* commands operating on sorted sets */
  799. 'zadd' => '\Predis\Commands\ZSetAdd',
  800. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  801. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  802. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  803. 'zrem' => '\Predis\Commands\ZSetRemove',
  804. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  805. 'zrange' => '\Predis\Commands\ZSetRange',
  806. 'zsetRange' => '\Predis\Commands\ZSetRange',
  807. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  808. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  809. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  810. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  811. 'zcard' => '\Predis\Commands\ZSetCardinality',
  812. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  813. 'zscore' => '\Predis\Commands\ZSetScore',
  814. 'zsetScore' => '\Predis\Commands\ZSetScore',
  815. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  816. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore'
  817. ));
  818. }
  819. }
  820. class RedisServer__Futures extends RedisServer__V1_2 {
  821. public function getVersion() { return 'DEV'; }
  822. public function getSupportedCommands() {
  823. return array_merge(parent::getSupportedCommands(), array(
  824. 'multi' => '\Predis\Commands\Multi',
  825. 'exec' => '\Predis\Commands\Exec'
  826. ));
  827. }
  828. }
  829. /* ------------------------------------------------------------------------- */
  830. namespace Predis\Utilities;
  831. class HashRing {
  832. const DEFAULT_REPLICAS = 128;
  833. private $_ring, $_ringKeys, $_replicas;
  834. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  835. $this->_replicas = $replicas;
  836. $this->_ring = array();
  837. $this->_ringKeys = array();
  838. }
  839. public function add($node) {
  840. $nodeHash = (string) $node;
  841. $replicas = $this->_replicas;
  842. for ($i = 0; $i < $replicas; $i++) {
  843. $key = crc32($nodeHash . ':' . $i);
  844. $this->_ring[$key] = $node;
  845. }
  846. ksort($this->_ring, SORT_NUMERIC);
  847. $this->_ringKeys = array_keys($this->_ring);
  848. }
  849. public function remove($node) {
  850. $nodeHash = (string) $node;
  851. $replicas = $this->_replicas;
  852. for ($i = 0; $i < $replicas; $i++) {
  853. $key = crc32($nodeHash . ':' . $i);
  854. unset($this->_ring[$key]);
  855. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  856. return $rk !== $key;
  857. });
  858. }
  859. }
  860. public function get($key) {
  861. return $this->_ring[$this->getNodeKey($key)];
  862. }
  863. private function getNodeKey($key) {
  864. $ringKeys = $this->_ringKeys;
  865. $upper = count($ringKeys) - 1;
  866. $lower = 0;
  867. $index = 0;
  868. while ($lower <= $upper) {
  869. $index = ($lower + $upper) / 2;
  870. $item = $ringKeys[$index];
  871. if ($item > $key) {
  872. $upper = $index - 1;
  873. }
  874. else if ($item < $key) {
  875. $lower = $index + 1;
  876. }
  877. else {
  878. return $index;
  879. }
  880. }
  881. return $ringKeys[$upper];
  882. }
  883. }
  884. /* ------------------------------------------------------------------------- */
  885. namespace Predis\Commands;
  886. /* miscellaneous commands */
  887. class Ping extends \Predis\InlineCommand {
  888. public function canBeHashed() { return false; }
  889. public function getCommandId() { return 'PING'; }
  890. public function parseResponse($data) {
  891. return $data === 'PONG' ? true : false;
  892. }
  893. }
  894. class DoEcho extends \Predis\BulkCommand {
  895. public function canBeHashed() { return false; }
  896. public function getCommandId() { return 'ECHO'; }
  897. }
  898. class Auth extends \Predis\InlineCommand {
  899. public function canBeHashed() { return false; }
  900. public function getCommandId() { return 'AUTH'; }
  901. }
  902. /* connection handling */
  903. class Quit extends \Predis\InlineCommand {
  904. public function canBeHashed() { return false; }
  905. public function getCommandId() { return 'QUIT'; }
  906. public function closesConnection() { return true; }
  907. }
  908. /* commands operating on string values */
  909. class Set extends \Predis\BulkCommand {
  910. public function getCommandId() { return 'SET'; }
  911. }
  912. class SetPreserve extends \Predis\BulkCommand {
  913. public function getCommandId() { return 'SETNX'; }
  914. public function parseResponse($data) { return (bool) $data; }
  915. }
  916. class SetMultiple extends \Predis\MultiBulkCommand {
  917. public function canBeHashed() { return false; }
  918. public function getCommandId() { return 'MSET'; }
  919. }
  920. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  921. public function canBeHashed() { return false; }
  922. public function getCommandId() { return 'MSETNX'; }
  923. public function parseResponse($data) { return (bool) $data; }
  924. }
  925. class Get extends \Predis\InlineCommand {
  926. public function getCommandId() { return 'GET'; }
  927. }
  928. class GetMultiple extends \Predis\InlineCommand {
  929. public function canBeHashed() { return false; }
  930. public function getCommandId() { return 'MGET'; }
  931. }
  932. class GetSet extends \Predis\BulkCommand {
  933. public function getCommandId() { return 'GETSET'; }
  934. }
  935. class Increment extends \Predis\InlineCommand {
  936. public function getCommandId() { return 'INCR'; }
  937. }
  938. class IncrementBy extends \Predis\InlineCommand {
  939. public function getCommandId() { return 'INCRBY'; }
  940. }
  941. class Decrement extends \Predis\InlineCommand {
  942. public function getCommandId() { return 'DECR'; }
  943. }
  944. class DecrementBy extends \Predis\InlineCommand {
  945. public function getCommandId() { return 'DECRBY'; }
  946. }
  947. class Exists extends \Predis\InlineCommand {
  948. public function getCommandId() { return 'EXISTS'; }
  949. public function parseResponse($data) { return (bool) $data; }
  950. }
  951. class Delete extends \Predis\InlineCommand {
  952. public function getCommandId() { return 'DEL'; }
  953. public function parseResponse($data) { return (bool) $data; }
  954. }
  955. class Type extends \Predis\InlineCommand {
  956. public function getCommandId() { return 'TYPE'; }
  957. }
  958. /* commands operating on the key space */
  959. class Keys extends \Predis\InlineCommand {
  960. public function canBeHashed() { return false; }
  961. public function getCommandId() { return 'KEYS'; }
  962. public function parseResponse($data) {
  963. // TODO: is this behaviour correct?
  964. return strlen($data) > 0 ? explode(' ', $data) : array();
  965. }
  966. }
  967. class RandomKey extends \Predis\InlineCommand {
  968. public function canBeHashed() { return false; }
  969. public function getCommandId() { return 'RANDOMKEY'; }
  970. public function parseResponse($data) { return $data !== '' ? $data : null; }
  971. }
  972. class Rename extends \Predis\InlineCommand {
  973. // TODO: doesn't RENAME break the hash-based client-side sharding?
  974. public function canBeHashed() { return false; }
  975. public function getCommandId() { return 'RENAME'; }
  976. }
  977. class RenamePreserve extends \Predis\InlineCommand {
  978. public function canBeHashed() { return false; }
  979. public function getCommandId() { return 'RENAMENX'; }
  980. public function parseResponse($data) { return (bool) $data; }
  981. }
  982. class Expire extends \Predis\InlineCommand {
  983. public function getCommandId() { return 'EXPIRE'; }
  984. public function parseResponse($data) { return (bool) $data; }
  985. }
  986. class ExpireAt extends \Predis\InlineCommand {
  987. public function getCommandId() { return 'EXPIREAT'; }
  988. public function parseResponse($data) { return (bool) $data; }
  989. }
  990. class DatabaseSize extends \Predis\InlineCommand {
  991. public function canBeHashed() { return false; }
  992. public function getCommandId() { return 'DBSIZE'; }
  993. }
  994. class TimeToLive extends \Predis\InlineCommand {
  995. public function getCommandId() { return 'TTL'; }
  996. }
  997. /* commands operating on lists */
  998. class ListPushTail extends \Predis\BulkCommand {
  999. public function getCommandId() { return 'RPUSH'; }
  1000. }
  1001. class ListPushHead extends \Predis\BulkCommand {
  1002. public function getCommandId() { return 'LPUSH'; }
  1003. }
  1004. class ListLength extends \Predis\InlineCommand {
  1005. public function getCommandId() { return 'LLEN'; }
  1006. }
  1007. class ListRange extends \Predis\InlineCommand {
  1008. public function getCommandId() { return 'LRANGE'; }
  1009. }
  1010. class ListTrim extends \Predis\InlineCommand {
  1011. public function getCommandId() { return 'LTRIM'; }
  1012. }
  1013. class ListIndex extends \Predis\InlineCommand {
  1014. public function getCommandId() { return 'LINDEX'; }
  1015. }
  1016. class ListSet extends \Predis\BulkCommand {
  1017. public function getCommandId() { return 'LSET'; }
  1018. }
  1019. class ListRemove extends \Predis\BulkCommand {
  1020. public function getCommandId() { return 'LREM'; }
  1021. }
  1022. class ListPopLastPushHead extends \Predis\BulkCommand {
  1023. public function getCommandId() { return 'RPOPLPUSH'; }
  1024. }
  1025. class ListPopFirst extends \Predis\InlineCommand {
  1026. public function getCommandId() { return 'LPOP'; }
  1027. }
  1028. class ListPopLast extends \Predis\InlineCommand {
  1029. public function getCommandId() { return 'RPOP'; }
  1030. }
  1031. /* commands operating on sets */
  1032. class SetAdd extends \Predis\BulkCommand {
  1033. public function getCommandId() { return 'SADD'; }
  1034. public function parseResponse($data) { return (bool) $data; }
  1035. }
  1036. class SetRemove extends \Predis\BulkCommand {
  1037. public function getCommandId() { return 'SREM'; }
  1038. public function parseResponse($data) { return (bool) $data; }
  1039. }
  1040. class SetPop extends \Predis\InlineCommand {
  1041. public function getCommandId() { return 'SPOP'; }
  1042. }
  1043. class SetMove extends \Predis\BulkCommand {
  1044. public function canBeHashed() { return false; }
  1045. public function getCommandId() { return 'SMOVE'; }
  1046. public function parseResponse($data) { return (bool) $data; }
  1047. }
  1048. class SetCardinality extends \Predis\InlineCommand {
  1049. public function getCommandId() { return 'SCARD'; }
  1050. }
  1051. class SetIsMember extends \Predis\BulkCommand {
  1052. public function getCommandId() { return 'SISMEMBER'; }
  1053. public function parseResponse($data) { return (bool) $data; }
  1054. }
  1055. class SetIntersection extends \Predis\InlineCommand {
  1056. public function getCommandId() { return 'SINTER'; }
  1057. }
  1058. class SetIntersectionStore extends \Predis\InlineCommand {
  1059. public function getCommandId() { return 'SINTERSTORE'; }
  1060. }
  1061. class SetUnion extends \Predis\InlineCommand {
  1062. public function getCommandId() { return 'SUNION'; }
  1063. }
  1064. class SetUnionStore extends \Predis\InlineCommand {
  1065. public function getCommandId() { return 'SUNIONSTORE'; }
  1066. }
  1067. class SetDifference extends \Predis\InlineCommand {
  1068. public function getCommandId() { return 'SDIFF'; }
  1069. }
  1070. class SetDifferenceStore extends \Predis\InlineCommand {
  1071. public function getCommandId() { return 'SDIFFSTORE'; }
  1072. }
  1073. class SetMembers extends \Predis\InlineCommand {
  1074. public function getCommandId() { return 'SMEMBERS'; }
  1075. }
  1076. class SetRandomMember extends \Predis\InlineCommand {
  1077. public function getCommandId() { return 'SRANDMEMBER'; }
  1078. }
  1079. /* commands operating on sorted sets */
  1080. class ZSetAdd extends \Predis\BulkCommand {
  1081. public function getCommandId() { return 'ZADD'; }
  1082. public function parseResponse($data) { return (bool) $data; }
  1083. }
  1084. class ZSetIncrementBy extends \Predis\BulkCommand {
  1085. public function getCommandId() { return 'ZINCRBY'; }
  1086. }
  1087. class ZSetRemove extends \Predis\BulkCommand {
  1088. public function getCommandId() { return 'ZREM'; }
  1089. public function parseResponse($data) { return (bool) $data; }
  1090. }
  1091. class ZSetRange extends \Predis\InlineCommand {
  1092. public function getCommandId() { return 'ZRANGE'; }
  1093. public function parseResponse($data) {
  1094. $arguments = $this->getArguments();
  1095. if (count($arguments) === 4) {
  1096. if (strtolower($arguments[3]) === 'withscores') {
  1097. $result = array();
  1098. for ($i = 0; $i < count($data); $i++) {
  1099. $result[] = array($data[$i], $data[++$i]);
  1100. }
  1101. return $result;
  1102. }
  1103. }
  1104. return $data;
  1105. }
  1106. }
  1107. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1108. public function getCommandId() { return 'ZREVRANGE'; }
  1109. }
  1110. class ZSetRangeByScore extends \Predis\InlineCommand {
  1111. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1112. }
  1113. class ZSetCardinality extends \Predis\InlineCommand {
  1114. public function getCommandId() { return 'ZCARD'; }
  1115. }
  1116. class ZSetScore extends \Predis\BulkCommand {
  1117. public function getCommandId() { return 'ZSCORE'; }
  1118. }
  1119. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1120. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1121. }
  1122. /* multiple databases handling commands */
  1123. class SelectDatabase extends \Predis\InlineCommand {
  1124. public function canBeHashed() { return false; }
  1125. public function getCommandId() { return 'SELECT'; }
  1126. }
  1127. class MoveKey extends \Predis\InlineCommand {
  1128. public function canBeHashed() { return false; }
  1129. public function getCommandId() { return 'MOVE'; }
  1130. public function parseResponse($data) { return (bool) $data; }
  1131. }
  1132. class FlushDatabase extends \Predis\InlineCommand {
  1133. public function canBeHashed() { return false; }
  1134. public function getCommandId() { return 'FLUSHDB'; }
  1135. }
  1136. class FlushAll extends \Predis\InlineCommand {
  1137. public function canBeHashed() { return false; }
  1138. public function getCommandId() { return 'FLUSHALL'; }
  1139. }
  1140. /* sorting */
  1141. class Sort extends \Predis\InlineCommand {
  1142. public function getCommandId() { return 'SORT'; }
  1143. public function filterArguments(Array $arguments) {
  1144. if (count($arguments) === 1) {
  1145. return $arguments;
  1146. }
  1147. // TODO: add more parameters checks
  1148. $query = array($arguments[0]);
  1149. $sortParams = $arguments[1];
  1150. if (isset($sortParams['by'])) {
  1151. $query[] = 'BY ' . $sortParams['by'];
  1152. }
  1153. if (isset($sortParams['get'])) {
  1154. $query[] = 'GET ' . $sortParams['get'];
  1155. }
  1156. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1157. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1158. }
  1159. if (isset($sortParams['sort'])) {
  1160. $query[] = strtoupper($sortParams['sort']);
  1161. }
  1162. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1163. $query[] = 'ALPHA';
  1164. }
  1165. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1166. $query[] = 'STORE ' . $sortParams['store'];
  1167. }
  1168. return $query;
  1169. }
  1170. }
  1171. /* persistence control commands */
  1172. class Save extends \Predis\InlineCommand {
  1173. public function canBeHashed() { return false; }
  1174. public function getCommandId() { return 'SAVE'; }
  1175. }
  1176. class BackgroundSave extends \Predis\InlineCommand {
  1177. public function canBeHashed() { return false; }
  1178. public function getCommandId() { return 'BGSAVE'; }
  1179. }
  1180. class LastSave extends \Predis\InlineCommand {
  1181. public function canBeHashed() { return false; }
  1182. public function getCommandId() { return 'LASTSAVE'; }
  1183. }
  1184. class Shutdown extends \Predis\InlineCommand {
  1185. public function canBeHashed() { return false; }
  1186. public function getCommandId() { return 'SHUTDOWN'; }
  1187. public function closesConnection() { return true; }
  1188. }
  1189. /* remote server control commands */
  1190. class Info extends \Predis\InlineCommand {
  1191. public function canBeHashed() { return false; }
  1192. public function getCommandId() { return 'INFO'; }
  1193. public function parseResponse($data) {
  1194. $info = array();
  1195. $infoLines = explode("\r\n", $data, -1);
  1196. foreach ($infoLines as $row) {
  1197. list($k, $v) = explode(':', $row);
  1198. if (!preg_match('/^db\d+$/', $k)) {
  1199. $info[$k] = $v;
  1200. }
  1201. else {
  1202. $db = array();
  1203. foreach (explode(',', $v) as $dbvar) {
  1204. list($dbvk, $dbvv) = explode('=', $dbvar);
  1205. $db[trim($dbvk)] = $dbvv;
  1206. }
  1207. $info[$k] = $db;
  1208. }
  1209. }
  1210. return $info;
  1211. }
  1212. }
  1213. class SlaveOf extends \Predis\InlineCommand {
  1214. public function canBeHashed() { return false; }
  1215. public function getCommandId() { return 'SLAVEOF'; }
  1216. public function filterArguments(Array $arguments) {
  1217. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1218. }
  1219. }
  1220. class Multi extends \Predis\InlineCommand {
  1221. public function canBeHashed() { return false; }
  1222. public function getCommandId() { return 'MULTI'; }
  1223. }
  1224. class Exec extends \Predis\InlineCommand {
  1225. public function canBeHashed() { return false; }
  1226. public function getCommandId() { return 'EXEC'; }
  1227. }
  1228. ?>