Predis.php 73 KB

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