Predis.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  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, $_responseReader;
  10. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  11. $this->_responseReader = new ResponseReader();
  12. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  13. $this->setupConnection($parameters);
  14. }
  15. public function __destruct() {
  16. $this->_connection->disconnect();
  17. }
  18. public static function create(/* arguments */) {
  19. $argv = func_get_args();
  20. $argc = func_num_args();
  21. $serverProfile = null;
  22. $lastArg = $argv[$argc-1];
  23. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  24. $serverProfile = array_pop($argv);
  25. $argc--;
  26. }
  27. if ($argc === 0) {
  28. throw new ClientException('Missing connection parameters');
  29. }
  30. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  31. }
  32. private function setupConnection($parameters) {
  33. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  34. throw new ClientException('Invalid parameters type (array or string expected)');
  35. }
  36. if (is_array($parameters) && isset($parameters[0])) {
  37. $cluster = new ConnectionCluster();
  38. foreach ($parameters as $shardParams) {
  39. $cluster->add($this->createConnection($shardParams));
  40. }
  41. $this->setConnection($cluster);
  42. }
  43. else {
  44. $this->setConnection($this->createConnection($parameters));
  45. }
  46. }
  47. private function createConnection($parameters) {
  48. $params = new ConnectionParameters($parameters);
  49. $connection = new Connection($params, $this->_responseReader);
  50. if ($params->password !== null) {
  51. $connection->pushInitCommand($this->createCommand(
  52. 'auth', array($params->password)
  53. ));
  54. }
  55. if ($params->database !== null) {
  56. $connection->pushInitCommand($this->createCommand(
  57. 'select', array($params->database)
  58. ));
  59. }
  60. return $connection;
  61. }
  62. private function setConnection(IConnection $connection) {
  63. $this->_connection = $connection;
  64. }
  65. public function setProfile(RedisServerProfile $serverProfile) {
  66. $this->_serverProfile = $serverProfile;
  67. }
  68. public function getProfile() {
  69. return $this->_serverProfile;
  70. }
  71. public function getResponseReader() {
  72. return $this->_responseReader;
  73. }
  74. public function connect() {
  75. $this->_connection->connect();
  76. }
  77. public function disconnect() {
  78. $this->_connection->disconnect();
  79. }
  80. public function isConnected() {
  81. return $this->_connection->isConnected();
  82. }
  83. public function getConnection($id = null) {
  84. if (!isset($id)) {
  85. return $this->_connection;
  86. }
  87. else {
  88. return $this->_connection instanceof ConnectionCluster
  89. ? $this->_connection->getConnectionById($id)
  90. : $this->_connection;
  91. }
  92. }
  93. public function __call($method, $arguments) {
  94. $command = $this->_serverProfile->createCommand($method, $arguments);
  95. return $this->_connection->executeCommand($command);
  96. }
  97. public function createCommand($method, $arguments = array()) {
  98. return $this->_serverProfile->createCommand($method, $arguments);
  99. }
  100. public function executeCommand(Command $command) {
  101. return $this->_connection->executeCommand($command);
  102. }
  103. public function executeCommandOnShards(Command $command) {
  104. $replies = array();
  105. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  106. foreach($this->_connection as $connection) {
  107. $replies[] = $connection->executeCommand($command);
  108. }
  109. }
  110. else {
  111. $replies[] = $this->_connection->executeCommand($command);
  112. }
  113. return $replies;
  114. }
  115. public function rawCommand($rawCommandData, $closesConnection = false) {
  116. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  117. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  118. }
  119. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  120. }
  121. public function pipeline($pipelineBlock = null) {
  122. $pipeline = new CommandPipeline($this);
  123. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  124. }
  125. public function multiExec($multiExecBlock = null) {
  126. $multiExec = new MultiExecBlock($this);
  127. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  128. }
  129. }
  130. /* ------------------------------------------------------------------------- */
  131. abstract class Command {
  132. private $_arguments, $_hash;
  133. public abstract function getCommandId();
  134. public abstract function serializeRequest($command, $arguments);
  135. public function canBeHashed() {
  136. return true;
  137. }
  138. public function getHash() {
  139. if (isset($this->_hash)) {
  140. return $this->_hash;
  141. }
  142. else {
  143. if (isset($this->_arguments[0])) {
  144. $key = $this->_arguments[0];
  145. $start = strpos($key, '{');
  146. $end = strpos($key, '}');
  147. if ($start !== false && $end !== false) {
  148. $key = substr($key, ++$start, $end - $start);
  149. }
  150. $this->_hash = crc32($key);
  151. return $this->_hash;
  152. }
  153. }
  154. return null;
  155. }
  156. public function closesConnection() {
  157. return false;
  158. }
  159. protected function filterArguments(Array $arguments) {
  160. return $arguments;
  161. }
  162. public function setArguments(/* arguments */) {
  163. $this->_arguments = $this->filterArguments(func_get_args());
  164. }
  165. public function setArgumentsArray(Array $arguments) {
  166. $this->_arguments = $this->filterArguments($arguments);
  167. }
  168. protected function getArguments() {
  169. // TODO: why getArguments is protected?
  170. return isset($this->_arguments) ? $this->_arguments : array();
  171. }
  172. public function getArgument($index = 0) {
  173. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  174. }
  175. public function parseResponse($data) {
  176. return $data;
  177. }
  178. public final function __invoke() {
  179. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  180. }
  181. }
  182. abstract class InlineCommand extends Command {
  183. public function serializeRequest($command, $arguments) {
  184. if (isset($arguments[0]) && is_array($arguments[0])) {
  185. $arguments[0] = implode($arguments[0], ' ');
  186. }
  187. return $command . ' ' . implode($arguments, ' ') . ResponseReader::NEWLINE;
  188. }
  189. }
  190. abstract class BulkCommand extends Command {
  191. public function serializeRequest($command, $arguments) {
  192. $data = array_pop($arguments);
  193. if (is_array($data)) {
  194. $data = implode($data, ' ');
  195. }
  196. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  197. ResponseReader::NEWLINE . $data . ResponseReader::NEWLINE;
  198. }
  199. }
  200. abstract class MultiBulkCommand extends Command {
  201. public function serializeRequest($command, $arguments) {
  202. $buffer = array();
  203. $cmd_args = null;
  204. if (count($arguments) === 1 && is_array($arguments[0])) {
  205. $cmd_args = array();
  206. foreach ($arguments[0] as $k => $v) {
  207. $cmd_args[] = $k;
  208. $cmd_args[] = $v;
  209. }
  210. }
  211. else {
  212. $cmd_args = $arguments;
  213. }
  214. $buffer[] = '*' . ((string) count($cmd_args) + 1) . ResponseReader::NEWLINE;
  215. $buffer[] = '$' . strlen($command) . ResponseReader::NEWLINE . $command . ResponseReader::NEWLINE;
  216. foreach ($cmd_args as $argument) {
  217. $buffer[] = '$' . strlen($argument) . ResponseReader::NEWLINE . $argument . ResponseReader::NEWLINE;
  218. }
  219. return implode('', $buffer);
  220. }
  221. }
  222. /* ------------------------------------------------------------------------- */
  223. interface IResponseHandler {
  224. function handle(Connection $connection, $payload);
  225. }
  226. class ResponseStatusHandler implements IResponseHandler {
  227. public function handle(Connection $connection, $status) {
  228. if ($status === ResponseReader::OK) {
  229. return true;
  230. }
  231. else if ($status === ResponseReader::QUEUED) {
  232. return new ResponseQueued();
  233. }
  234. return $status;
  235. }
  236. }
  237. class ResponseErrorHandler implements IResponseHandler {
  238. public function handle(Connection $connection, $errorMessage) {
  239. throw new ServerException(substr($errorMessage, 4));
  240. }
  241. }
  242. class ResponseErrorSilentHandler implements IResponseHandler {
  243. public function handle(Connection $connection, $errorMessage) {
  244. return new ResponseError(substr($errorMessage, 4));
  245. }
  246. }
  247. class ResponseBulkHandler implements IResponseHandler {
  248. public function handle(Connection $connection, $dataLength) {
  249. if (!is_numeric($dataLength)) {
  250. throw new ClientException("Cannot parse '$dataLength' as data length");
  251. }
  252. if ($dataLength > 0) {
  253. $value = $connection->readBytes($dataLength);
  254. if ($value === false) {
  255. throw new ClientException('An error has occurred while reading from the network stream');
  256. }
  257. $connection->readBytes(2);
  258. return $value;
  259. }
  260. else if ($dataLength == 0) {
  261. $connection->readBytes(2);
  262. return '';
  263. }
  264. return null;
  265. }
  266. }
  267. class ResponseMultiBulkHandler implements IResponseHandler {
  268. public function handle(Connection $connection, $rawLength) {
  269. if (!is_numeric($rawLength)) {
  270. throw new ClientException("Cannot parse '$rawLength' as data length");
  271. }
  272. $listLength = (int) $rawLength;
  273. if ($listLength === -1) {
  274. return null;
  275. }
  276. $list = array();
  277. if ($listLength > 0) {
  278. for ($i = 0; $i < $listLength; $i++) {
  279. $list[] = $connection->getResponseReader()->read($connection);
  280. }
  281. }
  282. return $list;
  283. }
  284. }
  285. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  286. public function handle(Connection $connection, $rawLength) {
  287. if (!is_numeric($rawLength)) {
  288. throw new ClientException("Cannot parse '$rawLength' as data length");
  289. }
  290. return new Utilities\MultiBulkResponseIterator($connection, (int)$rawLength);
  291. }
  292. }
  293. class ResponseIntegerHandler implements IResponseHandler {
  294. public function handle(Connection $connection, $number) {
  295. if (is_numeric($number)) {
  296. return (int) $number;
  297. }
  298. else {
  299. if ($number !== ResponseReader::NULL) {
  300. throw new ClientException("Cannot parse '$number' as numeric response");
  301. }
  302. return null;
  303. }
  304. }
  305. }
  306. class ResponseReader {
  307. const NEWLINE = "\r\n";
  308. const OK = 'OK';
  309. const ERROR = 'ERR';
  310. const QUEUED = 'QUEUED';
  311. const NULL = 'nil';
  312. const PREFIX_STATUS = '+';
  313. const PREFIX_ERROR = '-';
  314. const PREFIX_INTEGER = ':';
  315. const PREFIX_BULK = '$';
  316. const PREFIX_MULTI_BULK = '*';
  317. private $_prefixHandlers;
  318. public function __construct() {
  319. $this->initializePrefixHandlers();
  320. }
  321. private function initializePrefixHandlers() {
  322. $this->_prefixHandlers = array(
  323. self::PREFIX_STATUS => new ResponseStatusHandler(),
  324. self::PREFIX_ERROR => new ResponseErrorHandler(),
  325. self::PREFIX_INTEGER => new ResponseIntegerHandler(),
  326. self::PREFIX_BULK => new ResponseBulkHandler(),
  327. self::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  328. );
  329. }
  330. private function setHandler($prefix, IResponseHandler $handler) {
  331. $this->_prefixHandlers[$prefix] = $handler;
  332. }
  333. public function setOption($option, $value) {
  334. switch ($option) {
  335. case 'iterable_multibulk_replies':
  336. case 'iterableMultiBulkReplies':
  337. $this->setHandler(self::PREFIX_MULTI_BULK, $value == true
  338. ? new ResponseMultiBulkStreamHandler()
  339. : new ResponseMultiBulkHandler()
  340. );
  341. break;
  342. case 'errorThrowException':
  343. case 'error_throw_exception':
  344. $this->setHandler(self::PREFIX_ERROR, $value == true
  345. ? new ResponseErrorHandler()
  346. : new ResponseErrorSilentHandler()
  347. );
  348. break;
  349. default:
  350. throw new \InvalidArgumentException("Unknown option: $option");
  351. }
  352. }
  353. public function getOption($option) {
  354. switch ($option) {
  355. case 'iterable_multibulk_replies':
  356. case 'iterableMultiBulkReplies':
  357. return $this->_prefixHandlers[self::PREFIX_MULTI_BULK]
  358. instanceof ResponseMultiBulkStreamHandler;
  359. case 'errorThrowException':
  360. case 'error_throw_exception':
  361. return $this->_prefixHandlers[self::PREFIX_ERROR]
  362. instanceof ResponseErrorHandler;
  363. default:
  364. throw new \InvalidArgumentException("Unknown option: $option");
  365. }
  366. }
  367. public function read(Connection $connection) {
  368. $header = $connection->readLine();
  369. $prefix = $header[0];
  370. $payload = strlen($header) > 1 ? substr($header, 1) : '';
  371. if (!isset($this->_prefixHandlers[$prefix])) {
  372. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  373. }
  374. $handler = $this->_prefixHandlers[$prefix];
  375. return $handler->handle($connection, $payload);
  376. }
  377. }
  378. class ResponseError {
  379. private $_message;
  380. public function __construct($message) {
  381. $this->_message = $message;
  382. }
  383. public function __get($property) {
  384. if ($property == 'error') {
  385. return true;
  386. }
  387. if ($property == 'message') {
  388. return $this->_message;
  389. }
  390. }
  391. public function __isset($property) {
  392. return $property === 'error';
  393. }
  394. public function __toString() {
  395. return $this->_message;
  396. }
  397. }
  398. class ResponseQueued {
  399. public $queued = true;
  400. public function __toString() {
  401. return ResponseReader::QUEUED;
  402. }
  403. }
  404. /* ------------------------------------------------------------------------- */
  405. class CommandPipeline {
  406. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  407. public function __construct(Client $redisClient) {
  408. $this->_redisClient = $redisClient;
  409. $this->_pipelineBuffer = array();
  410. $this->_returnValues = array();
  411. }
  412. public function __call($method, $arguments) {
  413. $command = $this->_redisClient->createCommand($method, $arguments);
  414. $this->recordCommand($command);
  415. return $this;
  416. }
  417. private function recordCommand(Command $command) {
  418. $this->_pipelineBuffer[] = $command;
  419. }
  420. private function getRecordedCommands() {
  421. return $this->_pipelineBuffer;
  422. }
  423. public function flushPipeline() {
  424. $sizeofPipe = count($this->_pipelineBuffer);
  425. if ($sizeofPipe === 0) {
  426. return;
  427. }
  428. $connection = $this->_redisClient->getConnection();
  429. $commands = &$this->_pipelineBuffer;
  430. foreach ($commands as $command) {
  431. $connection->writeCommand($command);
  432. }
  433. for ($i = 0; $i < $sizeofPipe; $i++) {
  434. $response = $connection->readResponse($commands[$i]);
  435. $this->_returnValues[] = ($response instanceof \Iterator
  436. ? iterator_to_array($response)
  437. : $response
  438. );
  439. unset($commands[$i]);
  440. }
  441. $this->_pipelineBuffer = array();
  442. return $this;
  443. }
  444. private function setRunning($bool) {
  445. if ($bool == true && $this->_running == true) {
  446. throw new ClientException("This pipeline is already opened");
  447. }
  448. $this->_running = $bool;
  449. }
  450. public function execute($block = null) {
  451. if ($block && !is_callable($block)) {
  452. throw new \RuntimeException('Argument passed must be a callable object');
  453. }
  454. // TODO: do not reuse previously executed pipelines
  455. $this->setRunning(true);
  456. $pipelineBlockException = null;
  457. try {
  458. if ($block !== null) {
  459. $block($this);
  460. }
  461. $this->flushPipeline();
  462. }
  463. catch (\Exception $exception) {
  464. // TODO: client/server desync on ServerException
  465. $pipelineBlockException = $exception;
  466. }
  467. $this->setRunning(false);
  468. if ($pipelineBlockException !== null) {
  469. throw $pipelineBlockException;
  470. }
  471. return $this->_returnValues;
  472. }
  473. }
  474. class MultiExecBlock {
  475. private $_redisClient, $_commands, $_initialized, $_discarded;
  476. public function __construct(Client $redisClient) {
  477. $this->_initialized = false;
  478. $this->_discarded = false;
  479. $this->_redisClient = $redisClient;
  480. $this->_commands = array();
  481. }
  482. private function initialize() {
  483. if ($this->_initialized === false) {
  484. $this->_redisClient->multi();
  485. $this->_initialized = true;
  486. $this->_discarded = false;
  487. }
  488. }
  489. public function __call($method, $arguments) {
  490. $this->initialize();
  491. $command = $this->_redisClient->createCommand($method, $arguments);
  492. $response = $this->_redisClient->executeCommand($command);
  493. if (isset($response->queued)) {
  494. $this->_commands[] = $command;
  495. return $this;
  496. }
  497. else {
  498. throw new ClientException('The server did not respond with a QUEUED status reply');
  499. }
  500. }
  501. public function discard() {
  502. $this->_redisClient->discard();
  503. $this->_commands = array();
  504. $this->_initialized = false;
  505. $this->_discarded = true;
  506. }
  507. public function execute($block = null) {
  508. if ($block && !is_callable($block)) {
  509. throw new \RuntimeException('Argument passed must be a callable object');
  510. }
  511. $blockException = null;
  512. $returnValues = array();
  513. try {
  514. if ($block !== null) {
  515. $block($this);
  516. }
  517. if ($this->_discarded === true) {
  518. return;
  519. }
  520. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  521. ? iterator_to_array($reply)
  522. : $reply
  523. );
  524. $commands = &$this->_commands;
  525. $sizeofReplies = count($execReply);
  526. if ($sizeofReplies !== count($commands)) {
  527. // TODO: think of a better exception message
  528. throw new ClientException("Out-of-sync");
  529. }
  530. for ($i = 0; $i < $sizeofReplies; $i++) {
  531. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  532. ? iterator_to_array($execReply[$i])
  533. : $execReply[$i]
  534. );
  535. unset($commands[$i]);
  536. }
  537. }
  538. catch (\Exception $exception) {
  539. $blockException = $exception;
  540. }
  541. if ($blockException !== null) {
  542. throw $blockException;
  543. }
  544. return $returnValues;
  545. }
  546. }
  547. /* ------------------------------------------------------------------------- */
  548. class ConnectionParameters {
  549. const DEFAULT_HOST = '127.0.0.1';
  550. const DEFAULT_PORT = 6379;
  551. const DEFAULT_TIMEOUT = 5;
  552. private $_parameters;
  553. public function __construct($parameters = null) {
  554. $parameters = $parameters ?: array();
  555. $this->_parameters = is_array($parameters)
  556. ? self::filterConnectionParams($parameters)
  557. : self::parseURI($parameters);
  558. }
  559. private static function parseURI($uri) {
  560. $parsed = @parse_url($uri);
  561. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  562. throw new ClientException("Invalid URI: $uri");
  563. }
  564. if (array_key_exists('query', $parsed)) {
  565. $details = array();
  566. foreach (explode('&', $parsed['query']) as $kv) {
  567. list($k, $v) = explode('=', $kv);
  568. switch ($k) {
  569. case 'database':
  570. $details['database'] = $v;
  571. break;
  572. case 'password':
  573. $details['password'] = $v;
  574. break;
  575. case 'connection_timeout':
  576. $details['connection_timeout'] = $v;
  577. break;
  578. case 'read_write_timeout':
  579. $details['read_write_timeout'] = $v;
  580. break;
  581. case 'alias':
  582. $details['alias'] = $v;
  583. break;
  584. case 'weight':
  585. $details['weight'] = $v;
  586. break;
  587. }
  588. }
  589. $parsed = array_merge($parsed, $details);
  590. }
  591. return self::filterConnectionParams($parsed);
  592. }
  593. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  594. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  595. }
  596. private static function filterConnectionParams($parameters) {
  597. return array(
  598. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  599. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  600. 'database' => self::getParamOrDefault($parameters, 'database'),
  601. 'password' => self::getParamOrDefault($parameters, 'password'),
  602. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  603. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  604. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  605. 'weight' => self::getParamOrDefault($parameters, 'weight', Utilities\HashRing::DEFAULT_WEIGHT),
  606. );
  607. }
  608. public function __get($parameter) {
  609. return $this->_parameters[$parameter];
  610. }
  611. public function __isset($parameter) {
  612. return isset($this->_parameters[$parameter]);
  613. }
  614. }
  615. interface IConnection {
  616. public function connect();
  617. public function disconnect();
  618. public function isConnected();
  619. public function writeCommand(Command $command);
  620. public function readResponse(Command $command);
  621. public function executeCommand(Command $command);
  622. }
  623. class Connection implements IConnection {
  624. private $_params, $_socket, $_initCmds, $_reader;
  625. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  626. $this->_params = $parameters;
  627. $this->_initCmds = array();
  628. $this->_reader = $reader ?: new ResponseReader();
  629. }
  630. public function __destruct() {
  631. $this->disconnect();
  632. }
  633. public function isConnected() {
  634. return is_resource($this->_socket);
  635. }
  636. public function connect() {
  637. if ($this->isConnected()) {
  638. throw new ClientException('Connection already estabilished');
  639. }
  640. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  641. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  642. if (!$this->_socket) {
  643. throw new ClientException(trim($errstr), $errno);
  644. }
  645. if (isset($this->_params->read_write_timeout)) {
  646. $timeoutSeconds = floor($this->_params->read_write_timeout);
  647. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  648. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  649. }
  650. if (count($this->_initCmds) > 0){
  651. $this->sendInitializationCommands();
  652. }
  653. }
  654. public function disconnect() {
  655. if ($this->isConnected()) {
  656. fclose($this->_socket);
  657. }
  658. }
  659. public function pushInitCommand(Command $command){
  660. $this->_initCmds[] = $command;
  661. }
  662. private function sendInitializationCommands() {
  663. foreach ($this->_initCmds as $command) {
  664. $this->writeCommand($command);
  665. }
  666. foreach ($this->_initCmds as $command) {
  667. $this->readResponse($command);
  668. }
  669. }
  670. public function writeCommand(Command $command) {
  671. $written = $this->writeBytes($command());
  672. if ($written === false){
  673. throw new ClientException(sprintf(
  674. 'An error has occurred while writing command %s on the network stream',
  675. $command->getCommandId()
  676. ));
  677. }
  678. }
  679. public function readResponse(Command $command) {
  680. $response = $this->_reader->read($this);
  681. $skipparse = isset($response->queued) || isset($response->error);
  682. return $skipparse ? $response : $command->parseResponse($response);
  683. }
  684. public function executeCommand(Command $command) {
  685. $this->writeCommand($command);
  686. if ($command->closesConnection()) {
  687. return $this->disconnect();
  688. }
  689. return $this->readResponse($command);
  690. }
  691. public function rawCommand($rawCommandData, $closesConnection = false) {
  692. $written = $this->writeBytes($rawCommandData);
  693. if ($written === false){
  694. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  695. }
  696. if ($closesConnection) {
  697. $this->disconnect();
  698. return;
  699. }
  700. return $this->_reader->read($this);
  701. }
  702. public function writeBytes($value) {
  703. $socket = $this->getSocket();
  704. while (($length = strlen($value)) > 0) {
  705. $written = fwrite($socket, $value);
  706. if ($length === $written) {
  707. return true;
  708. }
  709. if ($written === false || $written === 0) {
  710. return false;
  711. }
  712. $value = substr($value, $written);
  713. }
  714. return true;
  715. }
  716. public function readBytes($length) {
  717. $socket = $this->getSocket();
  718. $value = '';
  719. do {
  720. $chunk = fread($socket, $length);
  721. if ($chunk === false || $chunk === '') {
  722. return false;
  723. }
  724. $value .= $chunk;
  725. }
  726. while (($length -= strlen($chunk)) > 0);
  727. return $value;
  728. }
  729. public function readLine() {
  730. $socket = $this->getSocket();
  731. $value = '';
  732. do {
  733. $chunk = fgets($socket);
  734. if ($chunk === false || strlen($chunk) == 0) {
  735. return false;
  736. }
  737. $value .= $chunk;
  738. }
  739. while (substr($value, -2) !== ResponseReader::NEWLINE);
  740. return substr($value, 0, -2);
  741. }
  742. public function getSocket() {
  743. if (!$this->isConnected()) {
  744. $this->connect();
  745. }
  746. return $this->_socket;
  747. }
  748. public function getResponseReader() {
  749. return $this->_reader;
  750. }
  751. public function getParameters() {
  752. return $this->_params;
  753. }
  754. public function __toString() {
  755. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  756. }
  757. }
  758. class ConnectionCluster implements IConnection, \IteratorAggregate {
  759. private $_pool, $_ring;
  760. public function __construct() {
  761. $this->_pool = array();
  762. $this->_ring = new Utilities\HashRing();
  763. }
  764. public function __destruct() {
  765. $this->disconnect();
  766. }
  767. public function isConnected() {
  768. foreach ($this->_pool as $connection) {
  769. if ($connection->isConnected()) {
  770. return true;
  771. }
  772. }
  773. return false;
  774. }
  775. public function connect() {
  776. foreach ($this->_pool as $connection) {
  777. $connection->connect();
  778. }
  779. }
  780. public function disconnect() {
  781. foreach ($this->_pool as $connection) {
  782. $connection->disconnect();
  783. }
  784. }
  785. public function add(Connection $connection) {
  786. $parameters = $connection->getParameters();
  787. if (isset($parameters->alias)) {
  788. $this->_pool[$parameters->alias] = $connection;
  789. }
  790. else {
  791. $this->_pool[] = $connection;
  792. }
  793. $this->_ring->add($connection, $parameters->weight);
  794. }
  795. public function getConnection(Command $command) {
  796. if ($command->canBeHashed() === false) {
  797. throw new ClientException(
  798. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  799. );
  800. }
  801. return $this->_ring->get($command->getHash());
  802. }
  803. public function getConnectionById($id = null) {
  804. return $this->_pool[$id ?: 0];
  805. }
  806. public function getIterator() {
  807. return new \ArrayIterator($this->_pool);
  808. }
  809. public function writeCommand(Command $command) {
  810. $this->getConnection($command)->writeCommand($command);
  811. }
  812. public function readResponse(Command $command) {
  813. return $this->getConnection($command)->readResponse($command);
  814. }
  815. public function executeCommand(Command $command) {
  816. $connection = $this->getConnection($command);
  817. $connection->writeCommand($command);
  818. return $connection->readResponse($command);
  819. }
  820. }
  821. /* ------------------------------------------------------------------------- */
  822. abstract class RedisServerProfile {
  823. private static $_serverProfiles;
  824. private $_registeredCommands;
  825. public function __construct() {
  826. $this->_registeredCommands = $this->getSupportedCommands();
  827. }
  828. public abstract function getVersion();
  829. protected abstract function getSupportedCommands();
  830. public static function getDefault() {
  831. return self::get('default');
  832. }
  833. private static function predisServerProfiles() {
  834. return array(
  835. '1.0' => '\Predis\RedisServer_v1_0',
  836. '1.2' => '\Predis\RedisServer_v1_2',
  837. 'default' => '\Predis\RedisServer_v1_2',
  838. 'dev' => '\Predis\RedisServer_vNext',
  839. );
  840. }
  841. public static function get($version) {
  842. if (!isset(self::$_serverProfiles)) {
  843. self::$_serverProfiles = self::predisServerProfiles();
  844. }
  845. if (!isset(self::$_serverProfiles[$version])) {
  846. throw new ClientException("Unknown server profile: $version");
  847. }
  848. $profile = self::$_serverProfiles[$version];
  849. return new $profile();
  850. }
  851. public function compareWith($version, $operator = null) {
  852. // one could expect that PHP's version_compare would behave
  853. // the same way if invoked with 2 arguments or 3 arguments
  854. // with the third being NULL, but it is not like that.
  855. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  856. // we might need to revise the behavior of this method.
  857. return ($operator === null
  858. ? version_compare($this, $version)
  859. : version_compare($this, $version, $operator)
  860. );
  861. }
  862. public function supportsCommand($command) {
  863. return isset($this->_registeredCommands[$command]);
  864. }
  865. public function createCommand($method, $arguments = array()) {
  866. if (!isset($this->_registeredCommands[$method])) {
  867. throw new ClientException("'$method' is not a registered Redis command");
  868. }
  869. $commandClass = $this->_registeredCommands[$method];
  870. $command = new $commandClass();
  871. $command->setArgumentsArray($arguments);
  872. return $command;
  873. }
  874. public function registerCommands(Array $commands) {
  875. foreach ($commands as $command => $aliases) {
  876. $this->registerCommand($command, $aliases);
  877. }
  878. }
  879. public function registerCommand($command, $aliases) {
  880. $commandReflection = new \ReflectionClass($command);
  881. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  882. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  883. }
  884. if (is_array($aliases)) {
  885. foreach ($aliases as $alias) {
  886. $this->_registeredCommands[$alias] = $command;
  887. }
  888. }
  889. else {
  890. $this->_registeredCommands[$aliases] = $command;
  891. }
  892. }
  893. public function __toString() {
  894. return $this->getVersion();
  895. }
  896. }
  897. class RedisServer_v1_0 extends RedisServerProfile {
  898. public function getVersion() { return '1.0'; }
  899. public function getSupportedCommands() {
  900. return array(
  901. /* miscellaneous commands */
  902. 'ping' => '\Predis\Commands\Ping',
  903. 'echo' => '\Predis\Commands\DoEcho',
  904. 'auth' => '\Predis\Commands\Auth',
  905. /* connection handling */
  906. 'quit' => '\Predis\Commands\Quit',
  907. /* commands operating on string values */
  908. 'set' => '\Predis\Commands\Set',
  909. 'setnx' => '\Predis\Commands\SetPreserve',
  910. 'setPreserve' => '\Predis\Commands\SetPreserve',
  911. 'get' => '\Predis\Commands\Get',
  912. 'mget' => '\Predis\Commands\GetMultiple',
  913. 'getMultiple' => '\Predis\Commands\GetMultiple',
  914. 'getset' => '\Predis\Commands\GetSet',
  915. 'getSet' => '\Predis\Commands\GetSet',
  916. 'incr' => '\Predis\Commands\Increment',
  917. 'increment' => '\Predis\Commands\Increment',
  918. 'incrby' => '\Predis\Commands\IncrementBy',
  919. 'incrementBy' => '\Predis\Commands\IncrementBy',
  920. 'decr' => '\Predis\Commands\Decrement',
  921. 'decrement' => '\Predis\Commands\Decrement',
  922. 'decrby' => '\Predis\Commands\DecrementBy',
  923. 'decrementBy' => '\Predis\Commands\DecrementBy',
  924. 'exists' => '\Predis\Commands\Exists',
  925. 'del' => '\Predis\Commands\Delete',
  926. 'delete' => '\Predis\Commands\Delete',
  927. 'type' => '\Predis\Commands\Type',
  928. /* commands operating on the key space */
  929. 'keys' => '\Predis\Commands\Keys',
  930. 'randomkey' => '\Predis\Commands\RandomKey',
  931. 'randomKey' => '\Predis\Commands\RandomKey',
  932. 'rename' => '\Predis\Commands\Rename',
  933. 'renamenx' => '\Predis\Commands\RenamePreserve',
  934. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  935. 'expire' => '\Predis\Commands\Expire',
  936. 'expireat' => '\Predis\Commands\ExpireAt',
  937. 'expireAt' => '\Predis\Commands\ExpireAt',
  938. 'dbsize' => '\Predis\Commands\DatabaseSize',
  939. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  940. 'ttl' => '\Predis\Commands\TimeToLive',
  941. 'timeToLive' => '\Predis\Commands\TimeToLive',
  942. /* commands operating on lists */
  943. 'rpush' => '\Predis\Commands\ListPushTail',
  944. 'pushTail' => '\Predis\Commands\ListPushTail',
  945. 'lpush' => '\Predis\Commands\ListPushHead',
  946. 'pushHead' => '\Predis\Commands\ListPushHead',
  947. 'llen' => '\Predis\Commands\ListLength',
  948. 'listLength' => '\Predis\Commands\ListLength',
  949. 'lrange' => '\Predis\Commands\ListRange',
  950. 'listRange' => '\Predis\Commands\ListRange',
  951. 'ltrim' => '\Predis\Commands\ListTrim',
  952. 'listTrim' => '\Predis\Commands\ListTrim',
  953. 'lindex' => '\Predis\Commands\ListIndex',
  954. 'listIndex' => '\Predis\Commands\ListIndex',
  955. 'lset' => '\Predis\Commands\ListSet',
  956. 'listSet' => '\Predis\Commands\ListSet',
  957. 'lrem' => '\Predis\Commands\ListRemove',
  958. 'listRemove' => '\Predis\Commands\ListRemove',
  959. 'lpop' => '\Predis\Commands\ListPopFirst',
  960. 'popFirst' => '\Predis\Commands\ListPopFirst',
  961. 'rpop' => '\Predis\Commands\ListPopLast',
  962. 'popLast' => '\Predis\Commands\ListPopLast',
  963. /* commands operating on sets */
  964. 'sadd' => '\Predis\Commands\SetAdd',
  965. 'setAdd' => '\Predis\Commands\SetAdd',
  966. 'srem' => '\Predis\Commands\SetRemove',
  967. 'setRemove' => '\Predis\Commands\SetRemove',
  968. 'spop' => '\Predis\Commands\SetPop',
  969. 'setPop' => '\Predis\Commands\SetPop',
  970. 'smove' => '\Predis\Commands\SetMove',
  971. 'setMove' => '\Predis\Commands\SetMove',
  972. 'scard' => '\Predis\Commands\SetCardinality',
  973. 'setCardinality' => '\Predis\Commands\SetCardinality',
  974. 'sismember' => '\Predis\Commands\SetIsMember',
  975. 'setIsMember' => '\Predis\Commands\SetIsMember',
  976. 'sinter' => '\Predis\Commands\SetIntersection',
  977. 'setIntersection' => '\Predis\Commands\SetIntersection',
  978. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  979. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  980. 'sunion' => '\Predis\Commands\SetUnion',
  981. 'setUnion' => '\Predis\Commands\SetUnion',
  982. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  983. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  984. 'sdiff' => '\Predis\Commands\SetDifference',
  985. 'setDifference' => '\Predis\Commands\SetDifference',
  986. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  987. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  988. 'smembers' => '\Predis\Commands\SetMembers',
  989. 'setMembers' => '\Predis\Commands\SetMembers',
  990. 'srandmember' => '\Predis\Commands\SetRandomMember',
  991. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  992. /* multiple databases handling commands */
  993. 'select' => '\Predis\Commands\SelectDatabase',
  994. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  995. 'move' => '\Predis\Commands\MoveKey',
  996. 'moveKey' => '\Predis\Commands\MoveKey',
  997. 'flushdb' => '\Predis\Commands\FlushDatabase',
  998. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  999. 'flushall' => '\Predis\Commands\FlushAll',
  1000. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1001. /* sorting */
  1002. 'sort' => '\Predis\Commands\Sort',
  1003. /* remote server control commands */
  1004. 'info' => '\Predis\Commands\Info',
  1005. 'slaveof' => '\Predis\Commands\SlaveOf',
  1006. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1007. /* persistence control commands */
  1008. 'save' => '\Predis\Commands\Save',
  1009. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1010. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1011. 'lastsave' => '\Predis\Commands\LastSave',
  1012. 'lastSave' => '\Predis\Commands\LastSave',
  1013. 'shutdown' => '\Predis\Commands\Shutdown',
  1014. );
  1015. }
  1016. }
  1017. class RedisServer_v1_2 extends RedisServer_v1_0 {
  1018. public function getVersion() { return '1.2'; }
  1019. public function getSupportedCommands() {
  1020. return array_merge(parent::getSupportedCommands(), array(
  1021. /* commands operating on string values */
  1022. 'mset' => '\Predis\Commands\SetMultiple',
  1023. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1024. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1025. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1026. /* commands operating on lists */
  1027. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  1028. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1029. /* commands operating on sorted sets */
  1030. 'zadd' => '\Predis\Commands\ZSetAdd',
  1031. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1032. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1033. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1034. 'zrem' => '\Predis\Commands\ZSetRemove',
  1035. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1036. 'zrange' => '\Predis\Commands\ZSetRange',
  1037. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1038. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1039. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1040. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1041. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1042. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1043. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1044. 'zscore' => '\Predis\Commands\ZSetScore',
  1045. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1046. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1047. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1048. /* persistence control commands */
  1049. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1050. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1051. ));
  1052. }
  1053. }
  1054. class RedisServer_vNext extends RedisServer_v1_2 {
  1055. public function getVersion() { return '1.3'; }
  1056. public function getSupportedCommands() {
  1057. return array_merge(parent::getSupportedCommands(), array(
  1058. /* miscellaneous commands */
  1059. 'multi' => '\Predis\Commands\Multi',
  1060. 'exec' => '\Predis\Commands\Exec',
  1061. 'discard' => '\Predis\Commands\Discard',
  1062. /* commands operating on string values */
  1063. 'append' => '\Predis\Commands\Append',
  1064. 'substr' => '\Predis\Commands\Substr',
  1065. /* commands operating on lists */
  1066. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1067. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1068. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1069. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1070. /* commands operating on sorted sets */
  1071. 'zunion' => '\Predis\Commands\ZSetUnion',
  1072. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1073. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1074. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1075. 'zcount' => '\Predis\Commands\ZSetCount',
  1076. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1077. 'zrank' => '\Predis\Commands\ZSetRank',
  1078. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1079. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1080. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1081. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1082. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1083. /* commands operating on hashes */
  1084. 'hset' => '\Predis\Commands\HashSet',
  1085. 'hashSet' => '\Predis\Commands\HashSet',
  1086. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1087. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1088. 'hget' => '\Predis\Commands\HashGet',
  1089. 'hashGet' => '\Predis\Commands\HashGet',
  1090. 'hdel' => '\Predis\Commands\HashDelete',
  1091. 'hashDelete' => '\Predis\Commands\HashDelete',
  1092. 'hexists' => '\Predis\Commands\HashExists',
  1093. 'hashExists' => '\Predis\Commands\HashExists',
  1094. 'hlen' => '\Predis\Commands\HashLength',
  1095. 'hashLength' => '\Predis\Commands\HashLength',
  1096. 'hkeys' => '\Predis\Commands\HashKeys',
  1097. 'hashKeys' => '\Predis\Commands\HashKeys',
  1098. 'hvals' => '\Predis\Commands\HashValues',
  1099. 'hashValues' => '\Predis\Commands\HashValues',
  1100. 'hgetall' => '\Predis\Commands\HashGetAll',
  1101. 'hashKeysValues' => '\Predis\Commands\HashGetAll',
  1102. /* remote server control commands */
  1103. 'config' => '\Predis\Commands\Config',
  1104. 'configuration' => '\Predis\Commands\Config',
  1105. ));
  1106. }
  1107. }
  1108. /* ------------------------------------------------------------------------- */
  1109. namespace Predis\Utilities;
  1110. class HashRing {
  1111. const DEFAULT_REPLICAS = 128;
  1112. const DEFAULT_WEIGHT = 100;
  1113. private $_nodes, $_ring, $_ringKeys, $_replicas;
  1114. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1115. $this->_replicas = $replicas;
  1116. $this->_nodes = array();
  1117. }
  1118. public function add($node, $weight = self::DEFAULT_WEIGHT) {
  1119. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1120. // last wins, thus the order in which nodes are added is significant.
  1121. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight);
  1122. $this->reset();
  1123. }
  1124. public function remove($node) {
  1125. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1126. // scratch, in order to reassign possible hashes with collisions to the
  1127. // right node according to the order in which they were added in the
  1128. // first place.
  1129. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1130. if ($this->_nodes[$i]['object'] === $node) {
  1131. array_splice($this->_nodes, $i, 1);
  1132. $this->reset();
  1133. break;
  1134. }
  1135. }
  1136. }
  1137. private function reset() {
  1138. unset($this->_ring);
  1139. unset($this->_ringKeys);
  1140. }
  1141. private function isInitialized() {
  1142. return isset($this->_ringKeys);
  1143. }
  1144. private function computeTotalWeight() {
  1145. // TODO: array_reduce + lambda for PHP 5.3
  1146. $totalWeight = 0;
  1147. foreach ($this->_nodes as $node) {
  1148. $totalWeight += $node['weight'];
  1149. }
  1150. return $totalWeight;
  1151. }
  1152. private function initialize() {
  1153. if ($this->isInitialized()) {
  1154. return;
  1155. }
  1156. if (count($this->_nodes) === 0) {
  1157. throw new \LogicException('Cannot initialize empty hashring');
  1158. }
  1159. $this->_ring = array();
  1160. $totalWeight = $this->computeTotalWeight();
  1161. $nodesCount = count($this->_nodes);
  1162. foreach ($this->_nodes as $node) {
  1163. $nodeObject = $node['object'];
  1164. $nodeHash = (string) $nodeObject;
  1165. $weightRatio = $node['weight'] / $totalWeight;
  1166. $replicas = (int) round($weightRatio * $nodesCount * $this->_replicas);
  1167. for ($i = 0; $i < $replicas; $i++) {
  1168. $key = crc32($nodeHash . ':' . $i);
  1169. $this->_ring[$key] = $nodeObject;
  1170. }
  1171. }
  1172. ksort($this->_ring, SORT_NUMERIC);
  1173. $this->_ringKeys = array_keys($this->_ring);
  1174. }
  1175. public function get($key) {
  1176. return $this->_ring[$this->getNodeKey($key)];
  1177. }
  1178. private function getNodeKey($key) {
  1179. // NOTE: binary search for the last item in _ringkeys with a value
  1180. // less or equal to the key. If no such item exists, return the
  1181. // last item.
  1182. $this->initialize();
  1183. $ringKeys = $this->_ringKeys;
  1184. $upper = count($ringKeys) - 1;
  1185. $lower = 0;
  1186. while ($lower <= $upper) {
  1187. $index = ($lower + $upper) >> 1;
  1188. $item = $ringKeys[$index];
  1189. if ($item > $key) {
  1190. $upper = $index - 1;
  1191. }
  1192. else if ($item < $key) {
  1193. $lower = $index + 1;
  1194. }
  1195. else {
  1196. return $item;
  1197. }
  1198. }
  1199. return $ringKeys[$upper >= 0 ? $upper : count($ringKeys) - 1];
  1200. }
  1201. }
  1202. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1203. protected $_position, $_current, $_replySize;
  1204. public function rewind() {
  1205. // NOOP
  1206. }
  1207. public function current() {
  1208. return $this->_current;
  1209. }
  1210. public function key() {
  1211. return $this->_position;
  1212. }
  1213. public function next() {
  1214. if (++$this->_position < $this->_replySize) {
  1215. $this->_current = $this->getValue();
  1216. }
  1217. return $this->_position;
  1218. }
  1219. public function valid() {
  1220. return $this->_position < $this->_replySize;
  1221. }
  1222. public function count() {
  1223. // NOTE: use count if you want to get the size of the current multi-bulk
  1224. // response without using iterator_count (which actually consumes
  1225. // our iterator to calculate the size, and we cannot perform a rewind)
  1226. return $this->_replySize;
  1227. }
  1228. protected abstract function getValue();
  1229. }
  1230. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1231. private $_connection;
  1232. public function __construct(\Predis\Connection $connection, $size) {
  1233. $this->_connection = $connection;
  1234. $this->_reader = $connection->getResponseReader();
  1235. $this->_position = 0;
  1236. $this->_current = $size > 0 ? $this->getValue() : null;
  1237. $this->_replySize = $size;
  1238. }
  1239. public function __destruct() {
  1240. // when the iterator is garbage-collected (e.g. it goes out of the
  1241. // scope of a foreach) but it has not reached its end, we must sync
  1242. // the client with the queued elements that have not been read from
  1243. // the connection with the server.
  1244. $this->sync();
  1245. }
  1246. public function sync() {
  1247. while ($this->valid()) {
  1248. $this->next();
  1249. }
  1250. }
  1251. protected function getValue() {
  1252. return $this->_reader->read($this->_connection);
  1253. }
  1254. }
  1255. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1256. private $_iterator;
  1257. public function __construct(MultiBulkResponseIterator $iterator) {
  1258. $virtualSize = count($iterator) / 2;
  1259. $this->_iterator = $iterator;
  1260. $this->_position = 0;
  1261. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1262. $this->_replySize = $virtualSize;
  1263. }
  1264. public function __destruct() {
  1265. $this->_iterator->sync();
  1266. }
  1267. protected function getValue() {
  1268. $k = $this->_iterator->current();
  1269. $this->_iterator->next();
  1270. $v = $this->_iterator->current();
  1271. $this->_iterator->next();
  1272. return array($k, $v);
  1273. }
  1274. }
  1275. /* ------------------------------------------------------------------------- */
  1276. namespace Predis\Commands;
  1277. /* miscellaneous commands */
  1278. class Ping extends \Predis\InlineCommand {
  1279. public function canBeHashed() { return false; }
  1280. public function getCommandId() { return 'PING'; }
  1281. public function parseResponse($data) {
  1282. return $data === 'PONG' ? true : false;
  1283. }
  1284. }
  1285. class DoEcho extends \Predis\BulkCommand {
  1286. public function canBeHashed() { return false; }
  1287. public function getCommandId() { return 'ECHO'; }
  1288. }
  1289. class Auth extends \Predis\InlineCommand {
  1290. public function canBeHashed() { return false; }
  1291. public function getCommandId() { return 'AUTH'; }
  1292. }
  1293. /* connection handling */
  1294. class Quit extends \Predis\InlineCommand {
  1295. public function canBeHashed() { return false; }
  1296. public function getCommandId() { return 'QUIT'; }
  1297. public function closesConnection() { return true; }
  1298. }
  1299. /* commands operating on string values */
  1300. class Set extends \Predis\BulkCommand {
  1301. public function getCommandId() { return 'SET'; }
  1302. }
  1303. class SetPreserve extends \Predis\BulkCommand {
  1304. public function getCommandId() { return 'SETNX'; }
  1305. public function parseResponse($data) { return (bool) $data; }
  1306. }
  1307. class SetMultiple extends \Predis\MultiBulkCommand {
  1308. public function canBeHashed() { return false; }
  1309. public function getCommandId() { return 'MSET'; }
  1310. }
  1311. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1312. public function canBeHashed() { return false; }
  1313. public function getCommandId() { return 'MSETNX'; }
  1314. public function parseResponse($data) { return (bool) $data; }
  1315. }
  1316. class Get extends \Predis\InlineCommand {
  1317. public function getCommandId() { return 'GET'; }
  1318. }
  1319. class GetMultiple extends \Predis\InlineCommand {
  1320. public function canBeHashed() { return false; }
  1321. public function getCommandId() { return 'MGET'; }
  1322. }
  1323. class GetSet extends \Predis\BulkCommand {
  1324. public function getCommandId() { return 'GETSET'; }
  1325. }
  1326. class Increment extends \Predis\InlineCommand {
  1327. public function getCommandId() { return 'INCR'; }
  1328. }
  1329. class IncrementBy extends \Predis\InlineCommand {
  1330. public function getCommandId() { return 'INCRBY'; }
  1331. }
  1332. class Decrement extends \Predis\InlineCommand {
  1333. public function getCommandId() { return 'DECR'; }
  1334. }
  1335. class DecrementBy extends \Predis\InlineCommand {
  1336. public function getCommandId() { return 'DECRBY'; }
  1337. }
  1338. class Exists extends \Predis\InlineCommand {
  1339. public function getCommandId() { return 'EXISTS'; }
  1340. public function parseResponse($data) { return (bool) $data; }
  1341. }
  1342. class Delete extends \Predis\InlineCommand {
  1343. public function getCommandId() { return 'DEL'; }
  1344. public function parseResponse($data) { return (bool) $data; }
  1345. }
  1346. class Type extends \Predis\InlineCommand {
  1347. public function getCommandId() { return 'TYPE'; }
  1348. }
  1349. class Append extends \Predis\BulkCommand {
  1350. public function getCommandId() { return 'APPEND'; }
  1351. }
  1352. class Substr extends \Predis\InlineCommand {
  1353. public function getCommandId() { return 'SUBSTR'; }
  1354. }
  1355. /* commands operating on the key space */
  1356. class Keys extends \Predis\InlineCommand {
  1357. public function canBeHashed() { return false; }
  1358. public function getCommandId() { return 'KEYS'; }
  1359. public function parseResponse($data) {
  1360. // TODO: is this behaviour correct?
  1361. if (is_array($data) || $data instanceof \Iterator) {
  1362. return $data;
  1363. }
  1364. return strlen($data) > 0 ? explode(' ', $data) : array();
  1365. }
  1366. }
  1367. class RandomKey extends \Predis\InlineCommand {
  1368. public function canBeHashed() { return false; }
  1369. public function getCommandId() { return 'RANDOMKEY'; }
  1370. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1371. }
  1372. class Rename extends \Predis\InlineCommand {
  1373. public function canBeHashed() { return false; }
  1374. public function getCommandId() { return 'RENAME'; }
  1375. }
  1376. class RenamePreserve extends \Predis\InlineCommand {
  1377. public function canBeHashed() { return false; }
  1378. public function getCommandId() { return 'RENAMENX'; }
  1379. public function parseResponse($data) { return (bool) $data; }
  1380. }
  1381. class Expire extends \Predis\InlineCommand {
  1382. public function getCommandId() { return 'EXPIRE'; }
  1383. public function parseResponse($data) { return (bool) $data; }
  1384. }
  1385. class ExpireAt extends \Predis\InlineCommand {
  1386. public function getCommandId() { return 'EXPIREAT'; }
  1387. public function parseResponse($data) { return (bool) $data; }
  1388. }
  1389. class DatabaseSize extends \Predis\InlineCommand {
  1390. public function canBeHashed() { return false; }
  1391. public function getCommandId() { return 'DBSIZE'; }
  1392. }
  1393. class TimeToLive extends \Predis\InlineCommand {
  1394. public function getCommandId() { return 'TTL'; }
  1395. }
  1396. /* commands operating on lists */
  1397. class ListPushTail extends \Predis\BulkCommand {
  1398. public function getCommandId() { return 'RPUSH'; }
  1399. }
  1400. class ListPushHead extends \Predis\BulkCommand {
  1401. public function getCommandId() { return 'LPUSH'; }
  1402. }
  1403. class ListLength extends \Predis\InlineCommand {
  1404. public function getCommandId() { return 'LLEN'; }
  1405. }
  1406. class ListRange extends \Predis\InlineCommand {
  1407. public function getCommandId() { return 'LRANGE'; }
  1408. }
  1409. class ListTrim extends \Predis\InlineCommand {
  1410. public function getCommandId() { return 'LTRIM'; }
  1411. }
  1412. class ListIndex extends \Predis\InlineCommand {
  1413. public function getCommandId() { return 'LINDEX'; }
  1414. }
  1415. class ListSet extends \Predis\BulkCommand {
  1416. public function getCommandId() { return 'LSET'; }
  1417. }
  1418. class ListRemove extends \Predis\BulkCommand {
  1419. public function getCommandId() { return 'LREM'; }
  1420. }
  1421. class ListPopLastPushHead extends \Predis\InlineCommand {
  1422. public function getCommandId() { return 'RPOPLPUSH'; }
  1423. }
  1424. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1425. public function getCommandId() { return 'RPOPLPUSH'; }
  1426. }
  1427. class ListPopFirst extends \Predis\InlineCommand {
  1428. public function getCommandId() { return 'LPOP'; }
  1429. }
  1430. class ListPopLast extends \Predis\InlineCommand {
  1431. public function getCommandId() { return 'RPOP'; }
  1432. }
  1433. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1434. public function getCommandId() { return 'BLPOP'; }
  1435. }
  1436. class ListPopLastBlocking extends \Predis\InlineCommand {
  1437. public function getCommandId() { return 'BRPOP'; }
  1438. }
  1439. /* commands operating on sets */
  1440. class SetAdd extends \Predis\BulkCommand {
  1441. public function getCommandId() { return 'SADD'; }
  1442. public function parseResponse($data) { return (bool) $data; }
  1443. }
  1444. class SetRemove extends \Predis\BulkCommand {
  1445. public function getCommandId() { return 'SREM'; }
  1446. public function parseResponse($data) { return (bool) $data; }
  1447. }
  1448. class SetPop extends \Predis\InlineCommand {
  1449. public function getCommandId() { return 'SPOP'; }
  1450. }
  1451. class SetMove extends \Predis\BulkCommand {
  1452. public function canBeHashed() { return false; }
  1453. public function getCommandId() { return 'SMOVE'; }
  1454. public function parseResponse($data) { return (bool) $data; }
  1455. }
  1456. class SetCardinality extends \Predis\InlineCommand {
  1457. public function getCommandId() { return 'SCARD'; }
  1458. }
  1459. class SetIsMember extends \Predis\BulkCommand {
  1460. public function getCommandId() { return 'SISMEMBER'; }
  1461. public function parseResponse($data) { return (bool) $data; }
  1462. }
  1463. class SetIntersection extends \Predis\InlineCommand {
  1464. public function getCommandId() { return 'SINTER'; }
  1465. }
  1466. class SetIntersectionStore extends \Predis\InlineCommand {
  1467. public function getCommandId() { return 'SINTERSTORE'; }
  1468. }
  1469. class SetUnion extends \Predis\InlineCommand {
  1470. public function getCommandId() { return 'SUNION'; }
  1471. }
  1472. class SetUnionStore extends \Predis\InlineCommand {
  1473. public function getCommandId() { return 'SUNIONSTORE'; }
  1474. }
  1475. class SetDifference extends \Predis\InlineCommand {
  1476. public function getCommandId() { return 'SDIFF'; }
  1477. }
  1478. class SetDifferenceStore extends \Predis\InlineCommand {
  1479. public function getCommandId() { return 'SDIFFSTORE'; }
  1480. }
  1481. class SetMembers extends \Predis\InlineCommand {
  1482. public function getCommandId() { return 'SMEMBERS'; }
  1483. }
  1484. class SetRandomMember extends \Predis\InlineCommand {
  1485. public function getCommandId() { return 'SRANDMEMBER'; }
  1486. }
  1487. /* commands operating on sorted sets */
  1488. class ZSetAdd extends \Predis\BulkCommand {
  1489. public function getCommandId() { return 'ZADD'; }
  1490. public function parseResponse($data) { return (bool) $data; }
  1491. }
  1492. class ZSetIncrementBy extends \Predis\BulkCommand {
  1493. public function getCommandId() { return 'ZINCRBY'; }
  1494. }
  1495. class ZSetRemove extends \Predis\BulkCommand {
  1496. public function getCommandId() { return 'ZREM'; }
  1497. public function parseResponse($data) { return (bool) $data; }
  1498. }
  1499. class ZSetUnion extends \Predis\InlineCommand {
  1500. public function getCommandId() { return 'ZUNION'; }
  1501. }
  1502. class ZSetIntersection extends \Predis\InlineCommand {
  1503. public function getCommandId() { return 'ZINTER'; }
  1504. }
  1505. class ZSetRange extends \Predis\InlineCommand {
  1506. public function getCommandId() { return 'ZRANGE'; }
  1507. public function parseResponse($data) {
  1508. $arguments = $this->getArguments();
  1509. if (count($arguments) === 4) {
  1510. if (strtolower($arguments[3]) === 'withscores') {
  1511. if ($data instanceof \Iterator) {
  1512. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1513. }
  1514. $result = array();
  1515. for ($i = 0; $i < count($data); $i++) {
  1516. $result[] = array($data[$i], $data[++$i]);
  1517. }
  1518. return $result;
  1519. }
  1520. }
  1521. return $data;
  1522. }
  1523. }
  1524. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1525. public function getCommandId() { return 'ZREVRANGE'; }
  1526. }
  1527. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1528. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1529. }
  1530. class ZSetCount extends \Predis\InlineCommand {
  1531. public function getCommandId() { return 'ZCOUNT'; }
  1532. }
  1533. class ZSetCardinality extends \Predis\InlineCommand {
  1534. public function getCommandId() { return 'ZCARD'; }
  1535. }
  1536. class ZSetScore extends \Predis\BulkCommand {
  1537. public function getCommandId() { return 'ZSCORE'; }
  1538. }
  1539. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1540. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1541. }
  1542. class ZSetRank extends \Predis\BulkCommand {
  1543. public function getCommandId() { return 'ZRANK'; }
  1544. }
  1545. class ZSetReverseRank extends \Predis\BulkCommand {
  1546. public function getCommandId() { return 'ZREVRANK'; }
  1547. }
  1548. class ZSetRemoveRangeByRank extends \Predis\InlineCommand {
  1549. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1550. }
  1551. /* commands operating on hashes */
  1552. class HashSet extends \Predis\MultiBulkCommand {
  1553. public function getCommandId() { return 'HSET'; }
  1554. }
  1555. class HashIncrementBy extends \Predis\InlineCommand {
  1556. public function getCommandId() { return 'HINCRBY'; }
  1557. }
  1558. class HashGet extends \Predis\BulkCommand {
  1559. public function getCommandId() { return 'HGET'; }
  1560. }
  1561. class HashDelete extends \Predis\BulkCommand {
  1562. public function getCommandId() { return 'HDEL'; }
  1563. }
  1564. class HashExists extends \Predis\BulkCommand {
  1565. public function getCommandId() { return 'HEXISTS'; }
  1566. }
  1567. class HashLength extends \Predis\InlineCommand {
  1568. public function getCommandId() { return 'HLEN'; }
  1569. }
  1570. class HashKeys extends \Predis\InlineCommand {
  1571. public function getCommandId() { return 'HKEYS'; }
  1572. }
  1573. class HashValues extends \Predis\InlineCommand {
  1574. public function getCommandId() { return 'HVALS'; }
  1575. }
  1576. class HashGetAll extends \Predis\InlineCommand {
  1577. public function getCommandId() { return 'HGETALL'; }
  1578. }
  1579. /* multiple databases handling commands */
  1580. class SelectDatabase extends \Predis\InlineCommand {
  1581. public function canBeHashed() { return false; }
  1582. public function getCommandId() { return 'SELECT'; }
  1583. }
  1584. class MoveKey extends \Predis\InlineCommand {
  1585. public function canBeHashed() { return false; }
  1586. public function getCommandId() { return 'MOVE'; }
  1587. public function parseResponse($data) { return (bool) $data; }
  1588. }
  1589. class FlushDatabase extends \Predis\InlineCommand {
  1590. public function canBeHashed() { return false; }
  1591. public function getCommandId() { return 'FLUSHDB'; }
  1592. }
  1593. class FlushAll extends \Predis\InlineCommand {
  1594. public function canBeHashed() { return false; }
  1595. public function getCommandId() { return 'FLUSHALL'; }
  1596. }
  1597. /* sorting */
  1598. class Sort extends \Predis\InlineCommand {
  1599. public function getCommandId() { return 'SORT'; }
  1600. public function filterArguments(Array $arguments) {
  1601. if (count($arguments) === 1) {
  1602. return $arguments;
  1603. }
  1604. // TODO: add more parameters checks
  1605. $query = array($arguments[0]);
  1606. $sortParams = $arguments[1];
  1607. if (isset($sortParams['by'])) {
  1608. $query[] = 'BY ' . $sortParams['by'];
  1609. }
  1610. if (isset($sortParams['get'])) {
  1611. $getargs = $sortParams['get'];
  1612. if (is_array($getargs)) {
  1613. foreach ($getargs as $getarg) {
  1614. $query[] = 'GET ' . $getarg;
  1615. }
  1616. }
  1617. else {
  1618. $query[] = 'GET ' . $getargs;
  1619. }
  1620. }
  1621. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1622. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1623. }
  1624. if (isset($sortParams['sort'])) {
  1625. $query[] = strtoupper($sortParams['sort']);
  1626. }
  1627. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1628. $query[] = 'ALPHA';
  1629. }
  1630. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1631. $query[] = 'STORE ' . $sortParams['store'];
  1632. }
  1633. return $query;
  1634. }
  1635. }
  1636. /* persistence control commands */
  1637. class Save extends \Predis\InlineCommand {
  1638. public function canBeHashed() { return false; }
  1639. public function getCommandId() { return 'SAVE'; }
  1640. }
  1641. class BackgroundSave extends \Predis\InlineCommand {
  1642. public function canBeHashed() { return false; }
  1643. public function getCommandId() { return 'BGSAVE'; }
  1644. public function parseResponse($data) {
  1645. if ($data == 'Background saving started') {
  1646. return true;
  1647. }
  1648. return $data;
  1649. }
  1650. }
  1651. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1652. public function canBeHashed() { return false; }
  1653. public function getCommandId() { return 'BGREWRITEAOF'; }
  1654. public function parseResponse($data) {
  1655. return $data == 'Background append only file rewriting started';
  1656. }
  1657. }
  1658. class LastSave extends \Predis\InlineCommand {
  1659. public function canBeHashed() { return false; }
  1660. public function getCommandId() { return 'LASTSAVE'; }
  1661. }
  1662. class Shutdown extends \Predis\InlineCommand {
  1663. public function canBeHashed() { return false; }
  1664. public function getCommandId() { return 'SHUTDOWN'; }
  1665. public function closesConnection() { return true; }
  1666. }
  1667. /* remote server control commands */
  1668. class Info extends \Predis\InlineCommand {
  1669. public function canBeHashed() { return false; }
  1670. public function getCommandId() { return 'INFO'; }
  1671. public function parseResponse($data) {
  1672. $info = array();
  1673. $infoLines = explode("\r\n", $data, -1);
  1674. foreach ($infoLines as $row) {
  1675. list($k, $v) = explode(':', $row);
  1676. if (!preg_match('/^db\d+$/', $k)) {
  1677. $info[$k] = $v;
  1678. }
  1679. else {
  1680. $db = array();
  1681. foreach (explode(',', $v) as $dbvar) {
  1682. list($dbvk, $dbvv) = explode('=', $dbvar);
  1683. $db[trim($dbvk)] = $dbvv;
  1684. }
  1685. $info[$k] = $db;
  1686. }
  1687. }
  1688. return $info;
  1689. }
  1690. }
  1691. class SlaveOf extends \Predis\InlineCommand {
  1692. public function canBeHashed() { return false; }
  1693. public function getCommandId() { return 'SLAVEOF'; }
  1694. public function filterArguments(Array $arguments) {
  1695. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1696. }
  1697. }
  1698. class Config extends \Predis\BulkCommand {
  1699. public function canBeHashed() { return false; }
  1700. public function getCommandId() { return 'CONFIG'; }
  1701. }
  1702. class Multi extends \Predis\InlineCommand {
  1703. public function canBeHashed() { return false; }
  1704. public function getCommandId() { return 'MULTI'; }
  1705. }
  1706. class Exec extends \Predis\InlineCommand {
  1707. public function canBeHashed() { return false; }
  1708. public function getCommandId() { return 'EXEC'; }
  1709. }
  1710. class Discard extends \Predis\InlineCommand {
  1711. public function canBeHashed() { return false; }
  1712. public function getCommandId() { return 'DISCARD'; }
  1713. }
  1714. ?>