Predis.php 50 KB

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