Predis.php 53 KB

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