Predis.php 50 KB

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