Predis.php 50 KB

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