Predis.php 51 KB

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