Predis.php 52 KB

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