Predis.php 49 KB

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