Predis.php 50 KB

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