Predis.php 50 KB

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