Predis.php 69 KB

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