Predis.php 50 KB

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