Predis.php 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  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. public function toResponseError() {
  7. return new ResponseError($this->getMessage());
  8. }
  9. }
  10. class CommunicationException extends PredisException { // Communication errors
  11. private $_connection;
  12. public function __construct(Connection $connection, $message = null, $code = null) {
  13. $this->_connection = $connection;
  14. parent::__construct($message, $code);
  15. }
  16. public function getConnection() { return $this->_connection; }
  17. public function shouldResetConnection() { return true; }
  18. }
  19. class MalformedServerResponse extends CommunicationException { } // Unexpected responses
  20. /* ------------------------------------------------------------------------- */
  21. class Client {
  22. private $_options, $_connection, $_serverProfile, $_responseReader;
  23. public function __construct($parameters = null, $clientOptions = null) {
  24. $this->setupClient($clientOptions ?: new ClientOptions());
  25. $this->setupConnection($parameters);
  26. }
  27. public static function create(/* arguments */) {
  28. $argv = func_get_args();
  29. $argc = func_num_args();
  30. $options = null;
  31. $lastArg = $argv[$argc-1];
  32. if ($argc > 0 && !is_string($lastArg) && ($lastArg instanceof ClientOptions ||
  33. is_subclass_of($lastArg, '\Predis\RedisServerProfile'))) {
  34. $options = array_pop($argv);
  35. $argc--;
  36. }
  37. if ($argc === 0) {
  38. throw new ClientException('Missing connection parameters');
  39. }
  40. return new Client($argc === 1 ? $argv[0] : $argv, $options);
  41. }
  42. private static function filterClientOptions($options) {
  43. if ($options instanceof ClientOptions) {
  44. return $options;
  45. }
  46. if (is_array($options)) {
  47. return new ClientOptions($options);
  48. }
  49. if ($options instanceof RedisServerProfile) {
  50. return new ClientOptions(array(
  51. 'profile' => $options
  52. ));
  53. }
  54. if (is_string($options)) {
  55. return new ClientOptions(array(
  56. 'profile' => RedisServerProfile::get($options)
  57. ));
  58. }
  59. throw new \InvalidArgumentException("Invalid type for client options");
  60. }
  61. private function setupClient($options) {
  62. $this->_responseReader = new ResponseReader();
  63. $this->_options = self::filterClientOptions($options);
  64. $this->setProfile($this->_options->profile);
  65. if ($this->_options->iterable_multibulk === true) {
  66. $this->_responseReader->setHandler(
  67. Protocol::PREFIX_MULTI_BULK,
  68. new ResponseMultiBulkStreamHandler()
  69. );
  70. }
  71. if ($this->_options->throw_on_error === false) {
  72. $this->_responseReader->setHandler(
  73. Protocol::PREFIX_ERROR,
  74. new ResponseErrorSilentHandler()
  75. );
  76. }
  77. }
  78. private function setupConnection($parameters) {
  79. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  80. throw new ClientException('Invalid parameters type (array or string expected)');
  81. }
  82. if (is_array($parameters) && isset($parameters[0])) {
  83. $cluster = new ConnectionCluster($this->_options->key_distribution);
  84. foreach ($parameters as $shardParams) {
  85. $cluster->add($this->createConnection($shardParams));
  86. }
  87. $this->setConnection($cluster);
  88. }
  89. else {
  90. $this->setConnection($this->createConnection($parameters));
  91. }
  92. }
  93. private function createConnection($parameters) {
  94. $params = new ConnectionParameters($parameters);
  95. $connection = new Connection($params, $this->_responseReader);
  96. if ($params->password !== null) {
  97. $connection->pushInitCommand($this->createCommand(
  98. 'auth', array($params->password)
  99. ));
  100. }
  101. if ($params->database !== null) {
  102. $connection->pushInitCommand($this->createCommand(
  103. 'select', array($params->database)
  104. ));
  105. }
  106. return $connection;
  107. }
  108. private function setConnection(IConnection $connection) {
  109. $this->_connection = $connection;
  110. }
  111. public function setProfile($serverProfile) {
  112. if (!($serverProfile instanceof RedisServerProfile || is_string($serverProfile))) {
  113. throw new \InvalidArgumentException(
  114. "Invalid type for server profile, \Predis\RedisServerProfile or string expected"
  115. );
  116. }
  117. $this->_serverProfile = (is_string($serverProfile)
  118. ? RedisServerProfile::get($serverProfile)
  119. : $serverProfile
  120. );
  121. }
  122. public function getProfile() {
  123. return $this->_serverProfile;
  124. }
  125. public function getResponseReader() {
  126. return $this->_responseReader;
  127. }
  128. public function getClientFor($connectionAlias) {
  129. if (!($this->_connection instanceof ConnectionCluster)) {
  130. throw new ClientException(
  131. 'This method is supported only when the client is connected to a cluster of connections'
  132. );
  133. }
  134. $connection = $this->_connection->getConnectionById($connectionAlias);
  135. if ($connection === null) {
  136. throw new \InvalidArgumentException(
  137. "Invalid connection alias: '$connectionAlias'"
  138. );
  139. }
  140. $newClient = new Client();
  141. $newClient->setupClient($this->_options);
  142. $newClient->setConnection($this->getConnection($connectionAlias));
  143. return $newClient;
  144. }
  145. public function connect() {
  146. $this->_connection->connect();
  147. }
  148. public function disconnect() {
  149. $this->_connection->disconnect();
  150. }
  151. public function isConnected() {
  152. return $this->_connection->isConnected();
  153. }
  154. public function getConnection($id = null) {
  155. if (!isset($id)) {
  156. return $this->_connection;
  157. }
  158. else {
  159. return $this->_connection instanceof ConnectionCluster
  160. ? $this->_connection->getConnectionById($id)
  161. : $this->_connection;
  162. }
  163. }
  164. public function __call($method, $arguments) {
  165. $command = $this->_serverProfile->createCommand($method, $arguments);
  166. return $this->_connection->executeCommand($command);
  167. }
  168. public function createCommand($method, $arguments = array()) {
  169. return $this->_serverProfile->createCommand($method, $arguments);
  170. }
  171. public function executeCommand(Command $command) {
  172. return $this->_connection->executeCommand($command);
  173. }
  174. public function executeCommandOnShards(Command $command) {
  175. $replies = array();
  176. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  177. foreach($this->_connection as $connection) {
  178. $replies[] = $connection->executeCommand($command);
  179. }
  180. }
  181. else {
  182. $replies[] = $this->_connection->executeCommand($command);
  183. }
  184. return $replies;
  185. }
  186. public function rawCommand($rawCommandData, $closesConnection = false) {
  187. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  188. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  189. }
  190. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  191. }
  192. public function pipeline($pipelineBlock = null) {
  193. return $this->pipelineExecute(new CommandPipeline($this), $pipelineBlock);
  194. }
  195. public function pipelineSafe($pipelineBlock = null) {
  196. $connection = $this->getConnection();
  197. $pipeline = new CommandPipeline($this, $connection instanceof Connection
  198. ? new Pipeline\SafeExecutor($connection)
  199. : new Pipeline\SafeClusterExecutor($connection)
  200. );
  201. return $this->pipelineExecute($pipeline, $pipelineBlock);
  202. }
  203. private function pipelineExecute(CommandPipeline $pipeline, $block) {
  204. return $block !== null ? $pipeline->execute($block) : $pipeline;
  205. }
  206. public function multiExec($multiExecBlock = null) {
  207. $multiExec = new MultiExecBlock($this);
  208. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  209. }
  210. public function pubSubContext() {
  211. return new PubSubContext($this);
  212. }
  213. }
  214. /* ------------------------------------------------------------------------- */
  215. interface IClientOptionsHandler {
  216. public function validate($option, $value);
  217. public function getDefault();
  218. }
  219. class ClientOptionsProfile implements IClientOptionsHandler {
  220. public function validate($option, $value) {
  221. if ($value instanceof \Predis\RedisServerProfile) {
  222. return $value;
  223. }
  224. if (is_string($value)) {
  225. return \Predis\RedisServerProfile::get($value);
  226. }
  227. throw new \InvalidArgumentException("Invalid value for option $option");
  228. }
  229. public function getDefault() {
  230. return \Predis\RedisServerProfile::getDefault();
  231. }
  232. }
  233. class ClientOptionsKeyDistribution implements IClientOptionsHandler {
  234. public function validate($option, $value) {
  235. if ($value instanceof \Predis\Distribution\IDistributionStrategy) {
  236. return $value;
  237. }
  238. if (is_string($value)) {
  239. $valueReflection = new \ReflectionClass($value);
  240. if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
  241. return new $value;
  242. }
  243. }
  244. throw new \InvalidArgumentException("Invalid value for option $option");
  245. }
  246. public function getDefault() {
  247. return new \Predis\Distribution\HashRing();
  248. }
  249. }
  250. class ClientOptionsIterableMultiBulk implements IClientOptionsHandler {
  251. public function validate($option, $value) {
  252. return (bool) $value;
  253. }
  254. public function getDefault() {
  255. return false;
  256. }
  257. }
  258. class ClientOptionsThrowOnError implements IClientOptionsHandler {
  259. public function validate($option, $value) {
  260. return (bool) $value;
  261. }
  262. public function getDefault() {
  263. return true;
  264. }
  265. }
  266. class ClientOptions {
  267. private static $_optionsHandlers;
  268. private $_options;
  269. public function __construct($options = null) {
  270. self::initializeOptionsHandlers();
  271. $this->initializeOptions($options ?: array());
  272. }
  273. private static function initializeOptionsHandlers() {
  274. if (!isset(self::$_optionsHandlers)) {
  275. self::$_optionsHandlers = self::getOptionsHandlers();
  276. }
  277. }
  278. private static function getOptionsHandlers() {
  279. return array(
  280. 'profile' => new \Predis\ClientOptionsProfile(),
  281. 'key_distribution' => new \Predis\ClientOptionsKeyDistribution(),
  282. 'iterable_multibulk' => new \Predis\ClientOptionsIterableMultiBulk(),
  283. 'throw_on_error' => new \Predis\ClientOptionsThrowOnError(),
  284. );
  285. }
  286. private function initializeOptions($options) {
  287. foreach ($options as $option => $value) {
  288. if (isset(self::$_optionsHandlers[$option])) {
  289. $handler = self::$_optionsHandlers[$option];
  290. $this->_options[$option] = $handler->validate($option, $value);
  291. }
  292. }
  293. }
  294. public function __get($option) {
  295. if (!isset($this->_options[$option])) {
  296. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  297. $this->_options[$option] = $defaultValue;
  298. }
  299. return $this->_options[$option];
  300. }
  301. public function __isset($option) {
  302. return isset(self::$_optionsHandlers[$option]);
  303. }
  304. }
  305. /* ------------------------------------------------------------------------- */
  306. class Protocol {
  307. const NEWLINE = "\r\n";
  308. const OK = 'OK';
  309. const ERROR = 'ERR';
  310. const QUEUED = 'QUEUED';
  311. const NULL = 'nil';
  312. const PREFIX_STATUS = '+';
  313. const PREFIX_ERROR = '-';
  314. const PREFIX_INTEGER = ':';
  315. const PREFIX_BULK = '$';
  316. const PREFIX_MULTI_BULK = '*';
  317. }
  318. abstract class Command {
  319. private $_arguments, $_hash;
  320. public abstract function getCommandId();
  321. public abstract function serializeRequest($command, $arguments);
  322. public function canBeHashed() {
  323. return true;
  324. }
  325. public function getHash(Distribution\IDistributionStrategy $distributor) {
  326. if (isset($this->_hash)) {
  327. return $this->_hash;
  328. }
  329. else {
  330. if (isset($this->_arguments[0])) {
  331. // TODO: should we throw an exception if the command does
  332. // not support sharding?
  333. $key = $this->_arguments[0];
  334. $start = strpos($key, '{');
  335. $end = strpos($key, '}');
  336. if ($start !== false && $end !== false) {
  337. $key = substr($key, ++$start, $end - $start);
  338. }
  339. $this->_hash = $distributor->generateKey($key);
  340. return $this->_hash;
  341. }
  342. }
  343. return null;
  344. }
  345. public function closesConnection() {
  346. return false;
  347. }
  348. protected function filterArguments(Array $arguments) {
  349. return $arguments;
  350. }
  351. public function setArguments(/* arguments */) {
  352. $this->_arguments = $this->filterArguments(func_get_args());
  353. $this->_hash = null;
  354. }
  355. public function setArgumentsArray(Array $arguments) {
  356. $this->_arguments = $this->filterArguments($arguments);
  357. $this->_hash = null;
  358. }
  359. public function getArguments() {
  360. return isset($this->_arguments) ? $this->_arguments : array();
  361. }
  362. public function getArgument($index = 0) {
  363. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  364. }
  365. public function parseResponse($data) {
  366. return $data;
  367. }
  368. public final function __invoke() {
  369. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  370. }
  371. }
  372. abstract class InlineCommand extends Command {
  373. public function serializeRequest($command, $arguments) {
  374. if (isset($arguments[0]) && is_array($arguments[0])) {
  375. $arguments[0] = implode($arguments[0], ' ');
  376. }
  377. return $command . (count($arguments) > 0
  378. ? ' ' . implode($arguments, ' ') . Protocol::NEWLINE
  379. : Protocol::NEWLINE
  380. );
  381. }
  382. }
  383. abstract class BulkCommand extends Command {
  384. public function serializeRequest($command, $arguments) {
  385. $data = array_pop($arguments);
  386. if (is_array($data)) {
  387. $data = implode($data, ' ');
  388. }
  389. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  390. Protocol::NEWLINE . $data . Protocol::NEWLINE;
  391. }
  392. }
  393. abstract class MultiBulkCommand extends Command {
  394. public function serializeRequest($command, $arguments) {
  395. $cmd_args = null;
  396. $argsc = count($arguments);
  397. if ($argsc === 1 && is_array($arguments[0])) {
  398. $cmd_args = $arguments[0];
  399. $argsc = count($cmd_args);
  400. }
  401. else {
  402. $cmd_args = $arguments;
  403. }
  404. $newline = Protocol::NEWLINE;
  405. $cmdlen = strlen($command);
  406. $reqlen = $argsc + 1;
  407. $buffer = "*{$reqlen}{$newline}\${$cmdlen}{$newline}{$command}{$newline}";
  408. foreach ($cmd_args as $argument) {
  409. $arglen = strlen($argument);
  410. $buffer .= "\${$arglen}{$newline}{$argument}{$newline}";
  411. }
  412. return $buffer;
  413. }
  414. }
  415. /* ------------------------------------------------------------------------- */
  416. interface IResponseHandler {
  417. function handle(Connection $connection, $payload);
  418. }
  419. class ResponseStatusHandler implements IResponseHandler {
  420. public function handle(Connection $connection, $status) {
  421. if ($status === Protocol::OK) {
  422. return true;
  423. }
  424. else if ($status === Protocol::QUEUED) {
  425. return new ResponseQueued();
  426. }
  427. return $status;
  428. }
  429. }
  430. class ResponseErrorHandler implements IResponseHandler {
  431. public function handle(Connection $connection, $errorMessage) {
  432. throw new ServerException(substr($errorMessage, 4));
  433. }
  434. }
  435. class ResponseErrorSilentHandler implements IResponseHandler {
  436. public function handle(Connection $connection, $errorMessage) {
  437. return new ResponseError(substr($errorMessage, 4));
  438. }
  439. }
  440. class ResponseBulkHandler implements IResponseHandler {
  441. public function handle(Connection $connection, $dataLength) {
  442. if (!is_numeric($dataLength)) {
  443. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  444. $connection, "Cannot parse '$dataLength' as data length"
  445. ));
  446. }
  447. if ($dataLength > 0) {
  448. $value = $connection->readBytes($dataLength);
  449. self::discardNewLine($connection);
  450. return $value;
  451. }
  452. else if ($dataLength == 0) {
  453. self::discardNewLine($connection);
  454. return '';
  455. }
  456. return null;
  457. }
  458. private static function discardNewLine(Connection $connection) {
  459. if ($connection->readBytes(2) !== Protocol::NEWLINE) {
  460. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  461. $connection, 'Did not receive a new-line at the end of a bulk response'
  462. ));
  463. }
  464. }
  465. }
  466. class ResponseMultiBulkHandler implements IResponseHandler {
  467. public function handle(Connection $connection, $rawLength) {
  468. if (!is_numeric($rawLength)) {
  469. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  470. $connection, "Cannot parse '$rawLength' as data length"
  471. ));
  472. }
  473. $listLength = (int) $rawLength;
  474. if ($listLength === -1) {
  475. return null;
  476. }
  477. $list = array();
  478. if ($listLength > 0) {
  479. $reader = $connection->getResponseReader();
  480. for ($i = 0; $i < $listLength; $i++) {
  481. $list[] = $reader->read($connection);
  482. }
  483. }
  484. return $list;
  485. }
  486. }
  487. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  488. public function handle(Connection $connection, $rawLength) {
  489. if (!is_numeric($rawLength)) {
  490. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  491. $connection, "Cannot parse '$rawLength' as data length"
  492. ));
  493. }
  494. return new Shared\MultiBulkResponseIterator($connection, (int)$rawLength);
  495. }
  496. }
  497. class ResponseIntegerHandler implements IResponseHandler {
  498. public function handle(Connection $connection, $number) {
  499. if (is_numeric($number)) {
  500. return (int) $number;
  501. }
  502. else {
  503. if ($number !== Protocol::NULL) {
  504. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  505. $connection, "Cannot parse '$number' as numeric response"
  506. ));
  507. }
  508. return null;
  509. }
  510. }
  511. }
  512. class ResponseReader {
  513. private $_prefixHandlers;
  514. public function __construct() {
  515. $this->initializePrefixHandlers();
  516. }
  517. private function initializePrefixHandlers() {
  518. $this->_prefixHandlers = array(
  519. Protocol::PREFIX_STATUS => new ResponseStatusHandler(),
  520. Protocol::PREFIX_ERROR => new ResponseErrorHandler(),
  521. Protocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
  522. Protocol::PREFIX_BULK => new ResponseBulkHandler(),
  523. Protocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  524. );
  525. }
  526. public function setHandler($prefix, IResponseHandler $handler) {
  527. $this->_prefixHandlers[$prefix] = $handler;
  528. }
  529. public function getHandler($prefix) {
  530. if (isset($this->_prefixHandlers[$prefix])) {
  531. return $this->_prefixHandlers[$prefix];
  532. }
  533. }
  534. public function read(Connection $connection) {
  535. $header = $connection->readLine();
  536. if ($header === '') {
  537. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  538. $connection, 'Unexpected empty header'
  539. ));
  540. }
  541. $prefix = $header[0];
  542. $payload = strlen($header) > 1 ? substr($header, 1) : '';
  543. if (!isset($this->_prefixHandlers[$prefix])) {
  544. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  545. $connection, "Unknown prefix '$prefix'"
  546. ));
  547. }
  548. $handler = $this->_prefixHandlers[$prefix];
  549. return $handler->handle($connection, $payload);
  550. }
  551. }
  552. class ResponseError {
  553. private $_message;
  554. public function __construct($message) {
  555. $this->_message = $message;
  556. }
  557. public function __get($property) {
  558. if ($property == 'error') {
  559. return true;
  560. }
  561. if ($property == 'message') {
  562. return $this->_message;
  563. }
  564. }
  565. public function __isset($property) {
  566. return $property === 'error';
  567. }
  568. public function __toString() {
  569. return $this->_message;
  570. }
  571. }
  572. class ResponseQueued {
  573. public $queued = true;
  574. public function __toString() {
  575. return Protocol::QUEUED;
  576. }
  577. }
  578. /* ------------------------------------------------------------------------- */
  579. class CommandPipeline {
  580. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  581. public function __construct(Client $redisClient, Pipeline\IPipelineExecutor $executor = null) {
  582. $this->_redisClient = $redisClient;
  583. $this->_executor = $executor ?: new Pipeline\StandardExecutor();
  584. $this->_pipelineBuffer = array();
  585. $this->_returnValues = array();
  586. }
  587. public function __call($method, $arguments) {
  588. $command = $this->_redisClient->createCommand($method, $arguments);
  589. $this->recordCommand($command);
  590. return $this;
  591. }
  592. private function recordCommand(Command $command) {
  593. $this->_pipelineBuffer[] = $command;
  594. }
  595. private function getRecordedCommands() {
  596. return $this->_pipelineBuffer;
  597. }
  598. public function flushPipeline() {
  599. if (count($this->_pipelineBuffer) > 0) {
  600. $connection = $this->_redisClient->getConnection();
  601. $this->_returnValues = array_merge(
  602. $this->_returnValues,
  603. $this->_executor->execute($connection, $this->_pipelineBuffer)
  604. );
  605. $this->_pipelineBuffer = array();
  606. }
  607. return $this;
  608. }
  609. private function setRunning($bool) {
  610. if ($bool == true && $this->_running == true) {
  611. throw new ClientException("This pipeline is already opened");
  612. }
  613. $this->_running = $bool;
  614. }
  615. public function execute($block = null) {
  616. if ($block && !is_callable($block)) {
  617. throw new \InvalidArgumentException('Argument passed must be a callable object');
  618. }
  619. // TODO: do not reuse previously executed pipelines
  620. $this->setRunning(true);
  621. $pipelineBlockException = null;
  622. try {
  623. if ($block !== null) {
  624. $block($this);
  625. }
  626. $this->flushPipeline();
  627. }
  628. catch (\Exception $exception) {
  629. $pipelineBlockException = $exception;
  630. }
  631. $this->setRunning(false);
  632. if ($pipelineBlockException !== null) {
  633. throw $pipelineBlockException;
  634. }
  635. return $this->_returnValues;
  636. }
  637. }
  638. class MultiExecBlock {
  639. private $_redisClient, $_commands, $_initialized, $_discarded;
  640. public function __construct(Client $redisClient) {
  641. $this->_initialized = false;
  642. $this->_discarded = false;
  643. $this->_redisClient = $redisClient;
  644. $this->_commands = array();
  645. }
  646. private function initialize() {
  647. if ($this->_initialized === false) {
  648. $this->_redisClient->multi();
  649. $this->_initialized = true;
  650. $this->_discarded = false;
  651. }
  652. }
  653. public function __call($method, $arguments) {
  654. $this->initialize();
  655. $command = $this->_redisClient->createCommand($method, $arguments);
  656. $response = $this->_redisClient->executeCommand($command);
  657. if (isset($response->queued)) {
  658. $this->_commands[] = $command;
  659. return $this;
  660. }
  661. else {
  662. $this->malformedServerResponse('The server did not respond with a QUEUED status reply');
  663. }
  664. }
  665. public function discard() {
  666. $this->_redisClient->discard();
  667. $this->_commands = array();
  668. $this->_initialized = false;
  669. $this->_discarded = true;
  670. }
  671. public function execute($block = null) {
  672. if ($block && !is_callable($block)) {
  673. throw new \InvalidArgumentException('Argument passed must be a callable object');
  674. }
  675. $blockException = null;
  676. $returnValues = array();
  677. try {
  678. if ($block !== null) {
  679. $block($this);
  680. }
  681. if ($this->_discarded === true) {
  682. return;
  683. }
  684. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  685. ? iterator_to_array($reply)
  686. : $reply
  687. );
  688. $commands = &$this->_commands;
  689. $sizeofReplies = count($execReply);
  690. if ($sizeofReplies !== count($commands)) {
  691. $this->malformedServerResponse('Unexpected number of responses for a MultiExecBlock');
  692. }
  693. for ($i = 0; $i < $sizeofReplies; $i++) {
  694. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  695. ? iterator_to_array($execReply[$i])
  696. : $execReply[$i]
  697. );
  698. unset($commands[$i]);
  699. }
  700. }
  701. catch (\Exception $exception) {
  702. $blockException = $exception;
  703. }
  704. if ($blockException !== null) {
  705. throw $blockException;
  706. }
  707. return $returnValues;
  708. }
  709. private function malformedServerResponse($message) {
  710. // NOTE: a MULTI/EXEC block cannot be initialized on a clustered
  711. // connection, which means that Predis\Client::getConnection
  712. // will always return an instance of Predis\Connection.
  713. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  714. $this->_redisClient->getConnection(), $message
  715. ));
  716. }
  717. }
  718. class PubSubContext implements \Iterator {
  719. const SUBSCRIBE = 'subscribe';
  720. const UNSUBSCRIBE = 'unsubscribe';
  721. const PSUBSCRIBE = 'psubscribe';
  722. const PUNSUBSCRIBE = 'punsubscribe';
  723. const MESSAGE = 'message';
  724. const PMESSAGE = 'pmessage';
  725. private $_redisClient, $_subscriptions, $_isStillValid, $_position;
  726. public function __construct(Client $redisClient) {
  727. $this->_redisClient = $redisClient;
  728. $this->_isStillValid = true;
  729. $this->_subscriptions = false;
  730. }
  731. public function __destruct() {
  732. if ($this->valid()) {
  733. $this->_redisClient->unsubscribe();
  734. $this->_redisClient->punsubscribe();
  735. }
  736. }
  737. public function subscribe(/* arguments */) {
  738. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  739. $this->_subscriptions = true;
  740. }
  741. public function unsubscribe(/* arguments */) {
  742. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  743. }
  744. public function psubscribe(/* arguments */) {
  745. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  746. $this->_subscriptions = true;
  747. }
  748. public function punsubscribe(/* arguments */) {
  749. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  750. }
  751. public function closeContext() {
  752. if ($this->valid()) {
  753. // TODO: as an optimization, we should not send both
  754. // commands if one of them has not been issued.
  755. $this->unsubscribe();
  756. $this->punsubscribe();
  757. }
  758. }
  759. private function writeCommand($method, $arguments) {
  760. if (count($arguments) === 1 && is_array($arguments[0])) {
  761. $arguments = $arguments[0];
  762. }
  763. $command = $this->_redisClient->createCommand($method, $arguments);
  764. $this->_redisClient->getConnection()->writeCommand($command);
  765. }
  766. public function rewind() {
  767. // NOOP
  768. }
  769. public function current() {
  770. return $this->getValue();
  771. }
  772. public function key() {
  773. return $this->_position;
  774. }
  775. public function next() {
  776. if ($this->_isStillValid) {
  777. $this->_position++;
  778. }
  779. return $this->_position;
  780. }
  781. public function valid() {
  782. return $this->_subscriptions && $this->_isStillValid;
  783. }
  784. private function invalidate() {
  785. $this->_isStillValid = false;
  786. $this->_subscriptions = false;
  787. }
  788. private function getValue() {
  789. $reader = $this->_redisClient->getResponseReader();
  790. $connection = $this->_redisClient->getConnection();
  791. $response = $reader->read($connection);
  792. switch ($response[0]) {
  793. case self::SUBSCRIBE:
  794. case self::UNSUBSCRIBE:
  795. case self::PSUBSCRIBE:
  796. case self::PUNSUBSCRIBE:
  797. if ($response[2] === 0) {
  798. $this->invalidate();
  799. }
  800. case self::MESSAGE:
  801. return (object) array(
  802. 'kind' => $response[0],
  803. 'channel' => $response[1],
  804. 'payload' => $response[2],
  805. );
  806. case self::PMESSAGE:
  807. return (object) array(
  808. 'kind' => $response[0],
  809. 'pattern' => $response[1],
  810. 'channel' => $response[2],
  811. 'payload' => $response[3],
  812. );
  813. default:
  814. throw new \Predis\ClientException(
  815. "Received an unknown message type {$response[0]} inside of a pubsub context"
  816. );
  817. }
  818. }
  819. }
  820. /* ------------------------------------------------------------------------- */
  821. class ConnectionParameters {
  822. const DEFAULT_HOST = '127.0.0.1';
  823. const DEFAULT_PORT = 6379;
  824. const DEFAULT_TIMEOUT = 5;
  825. private $_parameters;
  826. public function __construct($parameters = null) {
  827. $parameters = $parameters ?: array();
  828. $this->_parameters = is_array($parameters)
  829. ? self::filterConnectionParams($parameters)
  830. : self::parseURI($parameters);
  831. }
  832. private static function parseURI($uri) {
  833. $parsed = @parse_url($uri);
  834. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  835. throw new ClientException("Invalid URI: $uri");
  836. }
  837. if (array_key_exists('query', $parsed)) {
  838. $details = array();
  839. foreach (explode('&', $parsed['query']) as $kv) {
  840. list($k, $v) = explode('=', $kv);
  841. switch ($k) {
  842. case 'database':
  843. $details['database'] = $v;
  844. break;
  845. case 'password':
  846. $details['password'] = $v;
  847. break;
  848. case 'connection_async':
  849. $details['connection_async'] = $v;
  850. break;
  851. case 'connection_persistent':
  852. $details['connection_persistent'] = $v;
  853. break;
  854. case 'connection_timeout':
  855. $details['connection_timeout'] = $v;
  856. break;
  857. case 'read_write_timeout':
  858. $details['read_write_timeout'] = $v;
  859. break;
  860. case 'alias':
  861. $details['alias'] = $v;
  862. break;
  863. case 'weight':
  864. $details['weight'] = $v;
  865. break;
  866. }
  867. }
  868. $parsed = array_merge($parsed, $details);
  869. }
  870. return self::filterConnectionParams($parsed);
  871. }
  872. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  873. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  874. }
  875. private static function filterConnectionParams($parameters) {
  876. return array(
  877. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  878. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  879. 'database' => self::getParamOrDefault($parameters, 'database'),
  880. 'password' => self::getParamOrDefault($parameters, 'password'),
  881. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  882. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  883. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  884. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  885. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  886. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  887. );
  888. }
  889. public function __get($parameter) {
  890. return $this->_parameters[$parameter];
  891. }
  892. public function __isset($parameter) {
  893. return isset($this->_parameters[$parameter]);
  894. }
  895. }
  896. interface IConnection {
  897. public function connect();
  898. public function disconnect();
  899. public function isConnected();
  900. public function writeCommand(Command $command);
  901. public function readResponse(Command $command);
  902. public function executeCommand(Command $command);
  903. }
  904. class Connection implements IConnection {
  905. private $_params, $_socket, $_initCmds, $_reader;
  906. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  907. $this->_params = $parameters;
  908. $this->_initCmds = array();
  909. $this->_reader = $reader ?: new ResponseReader();
  910. }
  911. public function __destruct() {
  912. if (!$this->_params->connection_persistent) {
  913. $this->disconnect();
  914. }
  915. }
  916. public function isConnected() {
  917. return is_resource($this->_socket);
  918. }
  919. public function connect() {
  920. if ($this->isConnected()) {
  921. throw new ClientException('Connection already estabilished');
  922. }
  923. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  924. $connectFlags = STREAM_CLIENT_CONNECT;
  925. if ($this->_params->connection_async) {
  926. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  927. }
  928. if ($this->_params->connection_persistent) {
  929. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  930. }
  931. $this->_socket = @stream_socket_client(
  932. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  933. );
  934. if (!$this->_socket) {
  935. $this->onCommunicationException(trim($errstr), $errno);
  936. }
  937. if (isset($this->_params->read_write_timeout)) {
  938. $timeoutSeconds = floor($this->_params->read_write_timeout);
  939. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  940. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  941. }
  942. if (count($this->_initCmds) > 0){
  943. $this->sendInitializationCommands();
  944. }
  945. }
  946. public function disconnect() {
  947. if ($this->isConnected()) {
  948. fclose($this->_socket);
  949. }
  950. }
  951. public function pushInitCommand(Command $command){
  952. $this->_initCmds[] = $command;
  953. }
  954. private function sendInitializationCommands() {
  955. foreach ($this->_initCmds as $command) {
  956. $this->writeCommand($command);
  957. }
  958. foreach ($this->_initCmds as $command) {
  959. $this->readResponse($command);
  960. }
  961. }
  962. private function onCommunicationException($message, $code = null) {
  963. Shared\Utils::onCommunicationException(
  964. new CommunicationException($this, $message, $code)
  965. );
  966. }
  967. public function writeCommand(Command $command) {
  968. $this->writeBytes($command());
  969. }
  970. public function readResponse(Command $command) {
  971. $response = $this->_reader->read($this);
  972. $skipparse = isset($response->queued) || isset($response->error);
  973. return $skipparse ? $response : $command->parseResponse($response);
  974. }
  975. public function executeCommand(Command $command) {
  976. $this->writeCommand($command);
  977. if ($command->closesConnection()) {
  978. return $this->disconnect();
  979. }
  980. return $this->readResponse($command);
  981. }
  982. public function rawCommand($rawCommandData, $closesConnection = false) {
  983. $this->writeBytes($rawCommandData);
  984. if ($closesConnection) {
  985. $this->disconnect();
  986. return;
  987. }
  988. return $this->_reader->read($this);
  989. }
  990. public function writeBytes($value) {
  991. $socket = $this->getSocket();
  992. while (($length = strlen($value)) > 0) {
  993. $written = fwrite($socket, $value);
  994. if ($length === $written) {
  995. return true;
  996. }
  997. if ($written === false || $written === 0) {
  998. $this->onCommunicationException('Error while writing bytes to the server');
  999. }
  1000. $value = substr($value, $written);
  1001. }
  1002. return true;
  1003. }
  1004. public function readBytes($length) {
  1005. if ($length == 0) {
  1006. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1007. }
  1008. $socket = $this->getSocket();
  1009. $value = '';
  1010. do {
  1011. $chunk = fread($socket, $length);
  1012. if ($chunk === false || $chunk === '') {
  1013. $this->onCommunicationException('Error while reading bytes from the server');
  1014. }
  1015. $value .= $chunk;
  1016. }
  1017. while (($length -= strlen($chunk)) > 0);
  1018. return $value;
  1019. }
  1020. public function readLine() {
  1021. $socket = $this->getSocket();
  1022. $value = '';
  1023. do {
  1024. $chunk = fgets($socket);
  1025. if ($chunk === false || strlen($chunk) == 0) {
  1026. $this->onCommunicationException('Error while reading line from the server');
  1027. }
  1028. $value .= $chunk;
  1029. }
  1030. while (substr($value, -2) !== Protocol::NEWLINE);
  1031. return substr($value, 0, -2);
  1032. }
  1033. public function getSocket() {
  1034. if (!$this->isConnected()) {
  1035. $this->connect();
  1036. }
  1037. return $this->_socket;
  1038. }
  1039. public function getResponseReader() {
  1040. return $this->_reader;
  1041. }
  1042. public function getParameters() {
  1043. return $this->_params;
  1044. }
  1045. public function __toString() {
  1046. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1047. }
  1048. }
  1049. class ConnectionCluster implements IConnection, \IteratorAggregate {
  1050. private $_pool, $_distributor;
  1051. public function __construct(Distribution\IDistributionStrategy $distributor = null) {
  1052. $this->_pool = array();
  1053. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1054. }
  1055. public function isConnected() {
  1056. foreach ($this->_pool as $connection) {
  1057. if ($connection->isConnected()) {
  1058. return true;
  1059. }
  1060. }
  1061. return false;
  1062. }
  1063. public function connect() {
  1064. foreach ($this->_pool as $connection) {
  1065. $connection->connect();
  1066. }
  1067. }
  1068. public function disconnect() {
  1069. foreach ($this->_pool as $connection) {
  1070. $connection->disconnect();
  1071. }
  1072. }
  1073. public function add(Connection $connection) {
  1074. $parameters = $connection->getParameters();
  1075. if (isset($parameters->alias)) {
  1076. $this->_pool[$parameters->alias] = $connection;
  1077. }
  1078. else {
  1079. $this->_pool[] = $connection;
  1080. }
  1081. $this->_distributor->add($connection, $parameters->weight);
  1082. }
  1083. public function getConnection(Command $command) {
  1084. if ($command->canBeHashed() === false) {
  1085. throw new ClientException(
  1086. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1087. );
  1088. }
  1089. return $this->_distributor->get($command->getHash($this->_distributor));
  1090. }
  1091. public function getConnectionById($id = null) {
  1092. $alias = $id ?: 0;
  1093. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1094. }
  1095. public function getIterator() {
  1096. return new \ArrayIterator($this->_pool);
  1097. }
  1098. public function writeCommand(Command $command) {
  1099. $this->getConnection($command)->writeCommand($command);
  1100. }
  1101. public function readResponse(Command $command) {
  1102. return $this->getConnection($command)->readResponse($command);
  1103. }
  1104. public function executeCommand(Command $command) {
  1105. $connection = $this->getConnection($command);
  1106. $connection->writeCommand($command);
  1107. return $connection->readResponse($command);
  1108. }
  1109. }
  1110. /* ------------------------------------------------------------------------- */
  1111. abstract class RedisServerProfile {
  1112. private static $_serverProfiles;
  1113. private $_registeredCommands;
  1114. public function __construct() {
  1115. $this->_registeredCommands = $this->getSupportedCommands();
  1116. }
  1117. public abstract function getVersion();
  1118. protected abstract function getSupportedCommands();
  1119. public static function getDefault() {
  1120. return self::get('default');
  1121. }
  1122. public static function getDevelopment() {
  1123. return self::get('dev');
  1124. }
  1125. private static function predisServerProfiles() {
  1126. return array(
  1127. '1.2' => '\Predis\RedisServer_v1_2',
  1128. '2.0' => '\Predis\RedisServer_v2_0',
  1129. 'default' => '\Predis\RedisServer_v2_0',
  1130. 'dev' => '\Predis\RedisServer_vNext',
  1131. );
  1132. }
  1133. public static function registerProfile($profileClass, $aliases) {
  1134. if (!isset(self::$_serverProfiles)) {
  1135. self::$_serverProfiles = self::predisServerProfiles();
  1136. }
  1137. $profileReflection = new \ReflectionClass($profileClass);
  1138. if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
  1139. throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1140. }
  1141. if (is_array($aliases)) {
  1142. foreach ($aliases as $alias) {
  1143. self::$_serverProfiles[$alias] = $profileClass;
  1144. }
  1145. }
  1146. else {
  1147. self::$_serverProfiles[$aliases] = $profileClass;
  1148. }
  1149. }
  1150. public static function get($version) {
  1151. if (!isset(self::$_serverProfiles)) {
  1152. self::$_serverProfiles = self::predisServerProfiles();
  1153. }
  1154. if (!isset(self::$_serverProfiles[$version])) {
  1155. throw new ClientException("Unknown server profile: $version");
  1156. }
  1157. $profile = self::$_serverProfiles[$version];
  1158. return new $profile();
  1159. }
  1160. public function supportsCommand($command) {
  1161. return isset($this->_registeredCommands[$command]);
  1162. }
  1163. public function createCommand($method, $arguments = array()) {
  1164. if (!isset($this->_registeredCommands[$method])) {
  1165. throw new ClientException("'$method' is not a registered Redis command");
  1166. }
  1167. $commandClass = $this->_registeredCommands[$method];
  1168. $command = new $commandClass();
  1169. $command->setArgumentsArray($arguments);
  1170. return $command;
  1171. }
  1172. public function registerCommands(Array $commands) {
  1173. foreach ($commands as $command => $aliases) {
  1174. $this->registerCommand($command, $aliases);
  1175. }
  1176. }
  1177. public function registerCommand($command, $aliases) {
  1178. $commandReflection = new \ReflectionClass($command);
  1179. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  1180. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1181. }
  1182. if (is_array($aliases)) {
  1183. foreach ($aliases as $alias) {
  1184. $this->_registeredCommands[$alias] = $command;
  1185. }
  1186. }
  1187. else {
  1188. $this->_registeredCommands[$aliases] = $command;
  1189. }
  1190. }
  1191. public function __toString() {
  1192. return $this->getVersion();
  1193. }
  1194. }
  1195. class RedisServer_v1_2 extends RedisServerProfile {
  1196. public function getVersion() { return '1.2'; }
  1197. public function getSupportedCommands() {
  1198. return array(
  1199. /* miscellaneous commands */
  1200. 'ping' => '\Predis\Commands\Ping',
  1201. 'echo' => '\Predis\Commands\DoEcho',
  1202. 'auth' => '\Predis\Commands\Auth',
  1203. /* connection handling */
  1204. 'quit' => '\Predis\Commands\Quit',
  1205. /* commands operating on string values */
  1206. 'set' => '\Predis\Commands\Set',
  1207. 'setnx' => '\Predis\Commands\SetPreserve',
  1208. 'setPreserve' => '\Predis\Commands\SetPreserve',
  1209. 'mset' => '\Predis\Commands\SetMultiple',
  1210. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1211. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1212. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1213. 'get' => '\Predis\Commands\Get',
  1214. 'mget' => '\Predis\Commands\GetMultiple',
  1215. 'getMultiple' => '\Predis\Commands\GetMultiple',
  1216. 'getset' => '\Predis\Commands\GetSet',
  1217. 'getSet' => '\Predis\Commands\GetSet',
  1218. 'incr' => '\Predis\Commands\Increment',
  1219. 'increment' => '\Predis\Commands\Increment',
  1220. 'incrby' => '\Predis\Commands\IncrementBy',
  1221. 'incrementBy' => '\Predis\Commands\IncrementBy',
  1222. 'decr' => '\Predis\Commands\Decrement',
  1223. 'decrement' => '\Predis\Commands\Decrement',
  1224. 'decrby' => '\Predis\Commands\DecrementBy',
  1225. 'decrementBy' => '\Predis\Commands\DecrementBy',
  1226. 'exists' => '\Predis\Commands\Exists',
  1227. 'del' => '\Predis\Commands\Delete',
  1228. 'delete' => '\Predis\Commands\Delete',
  1229. 'type' => '\Predis\Commands\Type',
  1230. /* commands operating on the key space */
  1231. 'keys' => '\Predis\Commands\Keys',
  1232. 'randomkey' => '\Predis\Commands\RandomKey',
  1233. 'randomKey' => '\Predis\Commands\RandomKey',
  1234. 'rename' => '\Predis\Commands\Rename',
  1235. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1236. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  1237. 'expire' => '\Predis\Commands\Expire',
  1238. 'expireat' => '\Predis\Commands\ExpireAt',
  1239. 'expireAt' => '\Predis\Commands\ExpireAt',
  1240. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1241. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  1242. 'ttl' => '\Predis\Commands\TimeToLive',
  1243. 'timeToLive' => '\Predis\Commands\TimeToLive',
  1244. /* commands operating on lists */
  1245. 'rpush' => '\Predis\Commands\ListPushTail',
  1246. 'pushTail' => '\Predis\Commands\ListPushTail',
  1247. 'lpush' => '\Predis\Commands\ListPushHead',
  1248. 'pushHead' => '\Predis\Commands\ListPushHead',
  1249. 'llen' => '\Predis\Commands\ListLength',
  1250. 'listLength' => '\Predis\Commands\ListLength',
  1251. 'lrange' => '\Predis\Commands\ListRange',
  1252. 'listRange' => '\Predis\Commands\ListRange',
  1253. 'ltrim' => '\Predis\Commands\ListTrim',
  1254. 'listTrim' => '\Predis\Commands\ListTrim',
  1255. 'lindex' => '\Predis\Commands\ListIndex',
  1256. 'listIndex' => '\Predis\Commands\ListIndex',
  1257. 'lset' => '\Predis\Commands\ListSet',
  1258. 'listSet' => '\Predis\Commands\ListSet',
  1259. 'lrem' => '\Predis\Commands\ListRemove',
  1260. 'listRemove' => '\Predis\Commands\ListRemove',
  1261. 'lpop' => '\Predis\Commands\ListPopFirst',
  1262. 'popFirst' => '\Predis\Commands\ListPopFirst',
  1263. 'rpop' => '\Predis\Commands\ListPopLast',
  1264. 'popLast' => '\Predis\Commands\ListPopLast',
  1265. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1266. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1267. /* commands operating on sets */
  1268. 'sadd' => '\Predis\Commands\SetAdd',
  1269. 'setAdd' => '\Predis\Commands\SetAdd',
  1270. 'srem' => '\Predis\Commands\SetRemove',
  1271. 'setRemove' => '\Predis\Commands\SetRemove',
  1272. 'spop' => '\Predis\Commands\SetPop',
  1273. 'setPop' => '\Predis\Commands\SetPop',
  1274. 'smove' => '\Predis\Commands\SetMove',
  1275. 'setMove' => '\Predis\Commands\SetMove',
  1276. 'scard' => '\Predis\Commands\SetCardinality',
  1277. 'setCardinality' => '\Predis\Commands\SetCardinality',
  1278. 'sismember' => '\Predis\Commands\SetIsMember',
  1279. 'setIsMember' => '\Predis\Commands\SetIsMember',
  1280. 'sinter' => '\Predis\Commands\SetIntersection',
  1281. 'setIntersection' => '\Predis\Commands\SetIntersection',
  1282. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1283. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  1284. 'sunion' => '\Predis\Commands\SetUnion',
  1285. 'setUnion' => '\Predis\Commands\SetUnion',
  1286. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1287. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  1288. 'sdiff' => '\Predis\Commands\SetDifference',
  1289. 'setDifference' => '\Predis\Commands\SetDifference',
  1290. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1291. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  1292. 'smembers' => '\Predis\Commands\SetMembers',
  1293. 'setMembers' => '\Predis\Commands\SetMembers',
  1294. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1295. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  1296. /* commands operating on sorted sets */
  1297. 'zadd' => '\Predis\Commands\ZSetAdd',
  1298. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1299. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1300. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1301. 'zrem' => '\Predis\Commands\ZSetRemove',
  1302. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1303. 'zrange' => '\Predis\Commands\ZSetRange',
  1304. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1305. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1306. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1307. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1308. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1309. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1310. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1311. 'zscore' => '\Predis\Commands\ZSetScore',
  1312. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1313. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1314. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1315. /* multiple databases handling commands */
  1316. 'select' => '\Predis\Commands\SelectDatabase',
  1317. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  1318. 'move' => '\Predis\Commands\MoveKey',
  1319. 'moveKey' => '\Predis\Commands\MoveKey',
  1320. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1321. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  1322. 'flushall' => '\Predis\Commands\FlushAll',
  1323. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1324. /* sorting */
  1325. 'sort' => '\Predis\Commands\Sort',
  1326. /* remote server control commands */
  1327. 'info' => '\Predis\Commands\Info',
  1328. 'slaveof' => '\Predis\Commands\SlaveOf',
  1329. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1330. /* persistence control commands */
  1331. 'save' => '\Predis\Commands\Save',
  1332. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1333. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1334. 'lastsave' => '\Predis\Commands\LastSave',
  1335. 'lastSave' => '\Predis\Commands\LastSave',
  1336. 'shutdown' => '\Predis\Commands\Shutdown',
  1337. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1338. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1339. );
  1340. }
  1341. }
  1342. class RedisServer_v2_0 extends RedisServer_v1_2 {
  1343. public function getVersion() { return '2.0'; }
  1344. public function getSupportedCommands() {
  1345. return array_merge(parent::getSupportedCommands(), array(
  1346. /* transactions */
  1347. 'multi' => '\Predis\Commands\Multi',
  1348. 'exec' => '\Predis\Commands\Exec',
  1349. 'discard' => '\Predis\Commands\Discard',
  1350. /* commands operating on string values */
  1351. 'setex' => '\Predis\Commands\SetExpire',
  1352. 'setExpire' => '\Predis\Commands\SetExpire',
  1353. 'append' => '\Predis\Commands\Append',
  1354. 'substr' => '\Predis\Commands\Substr',
  1355. /* commands operating on lists */
  1356. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1357. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1358. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1359. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1360. /* commands operating on sorted sets */
  1361. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1362. 'zsetUnionStore' => '\Predis\Commands\ZSetUnionStore',
  1363. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1364. 'zsetIntersectionStore' => '\Predis\Commands\ZSetIntersectionStore',
  1365. 'zcount' => '\Predis\Commands\ZSetCount',
  1366. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1367. 'zrank' => '\Predis\Commands\ZSetRank',
  1368. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1369. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1370. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1371. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1372. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1373. /* commands operating on hashes */
  1374. 'hset' => '\Predis\Commands\HashSet',
  1375. 'hashSet' => '\Predis\Commands\HashSet',
  1376. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1377. 'hashSetPreserve' => '\Predis\Commands\HashSetPreserve',
  1378. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1379. 'hashSetMultiple' => '\Predis\Commands\HashSetMultiple',
  1380. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1381. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1382. 'hget' => '\Predis\Commands\HashGet',
  1383. 'hashGet' => '\Predis\Commands\HashGet',
  1384. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1385. 'hashGetMultiple' => '\Predis\Commands\HashGetMultiple',
  1386. 'hdel' => '\Predis\Commands\HashDelete',
  1387. 'hashDelete' => '\Predis\Commands\HashDelete',
  1388. 'hexists' => '\Predis\Commands\HashExists',
  1389. 'hashExists' => '\Predis\Commands\HashExists',
  1390. 'hlen' => '\Predis\Commands\HashLength',
  1391. 'hashLength' => '\Predis\Commands\HashLength',
  1392. 'hkeys' => '\Predis\Commands\HashKeys',
  1393. 'hashKeys' => '\Predis\Commands\HashKeys',
  1394. 'hvals' => '\Predis\Commands\HashValues',
  1395. 'hashValues' => '\Predis\Commands\HashValues',
  1396. 'hgetall' => '\Predis\Commands\HashGetAll',
  1397. 'hashGetAll' => '\Predis\Commands\HashGetAll',
  1398. /* publish - subscribe */
  1399. 'subscribe' => '\Predis\Commands\Subscribe',
  1400. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1401. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1402. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1403. 'publish' => '\Predis\Commands\Publish',
  1404. /* remote server control commands */
  1405. 'config' => '\Predis\Commands\Config',
  1406. 'configuration' => '\Predis\Commands\Config',
  1407. ));
  1408. }
  1409. }
  1410. class RedisServer_vNext extends RedisServer_v2_0 {
  1411. public function getVersion() { return '2.1'; }
  1412. public function getSupportedCommands() {
  1413. return array_merge(parent::getSupportedCommands(), array(
  1414. /* transactions */
  1415. 'watch' => '\Predis\Commands\Watch',
  1416. 'unwatch' => '\Predis\Commands\Unwatch',
  1417. ));
  1418. }
  1419. }
  1420. /* ------------------------------------------------------------------------- */
  1421. namespace Predis\Pipeline;
  1422. interface IPipelineExecutor {
  1423. public function execute(\Predis\IConnection $connection, &$commands);
  1424. }
  1425. class StandardExecutor implements IPipelineExecutor {
  1426. public function execute(\Predis\IConnection $connection, &$commands) {
  1427. $sizeofPipe = count($commands);
  1428. $values = array();
  1429. foreach ($commands as $command) {
  1430. $connection->writeCommand($command);
  1431. }
  1432. try {
  1433. for ($i = 0; $i < $sizeofPipe; $i++) {
  1434. $response = $connection->readResponse($commands[$i]);
  1435. $values[] = $response instanceof \Iterator
  1436. ? iterator_to_array($response)
  1437. : $response;
  1438. unset($commands[$i]);
  1439. }
  1440. }
  1441. catch (\Predis\ServerException $exception) {
  1442. // force disconnection to prevent protocol desynchronization
  1443. $connection->disconnect();
  1444. throw $exception;
  1445. }
  1446. return $values;
  1447. }
  1448. }
  1449. class SafeExecutor implements IPipelineExecutor {
  1450. public function execute(\Predis\IConnection $connection, &$commands) {
  1451. $sizeofPipe = count($commands);
  1452. $values = array();
  1453. foreach ($commands as $command) {
  1454. try {
  1455. $connection->writeCommand($command);
  1456. }
  1457. catch (\Predis\CommunicationException $exception) {
  1458. return array_fill(0, $sizeofPipe, $exception);
  1459. }
  1460. }
  1461. for ($i = 0; $i < $sizeofPipe; $i++) {
  1462. $command = $commands[$i];
  1463. unset($commands[$i]);
  1464. try {
  1465. $response = $connection->readResponse($command);
  1466. $values[] = ($response instanceof \Iterator
  1467. ? iterator_to_array($response)
  1468. : $response
  1469. );
  1470. }
  1471. catch (\Predis\ServerException $exception) {
  1472. $values[] = $exception->toResponseError();
  1473. }
  1474. catch (\Predis\CommunicationException $exception) {
  1475. $toAdd = count($commands) - count($values);
  1476. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1477. break;
  1478. }
  1479. }
  1480. return $values;
  1481. }
  1482. }
  1483. class SafeClusterExecutor implements IPipelineExecutor {
  1484. public function execute(\Predis\IConnection $connection, &$commands) {
  1485. $connectionExceptions = array();
  1486. $sizeofPipe = count($commands);
  1487. $values = array();
  1488. foreach ($commands as $command) {
  1489. $cmdConnection = $connection->getConnection($command);
  1490. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1491. continue;
  1492. }
  1493. try {
  1494. $cmdConnection->writeCommand($command);
  1495. }
  1496. catch (\Predis\CommunicationException $exception) {
  1497. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1498. }
  1499. }
  1500. for ($i = 0; $i < $sizeofPipe; $i++) {
  1501. $command = $commands[$i];
  1502. unset($commands[$i]);
  1503. $cmdConnection = $connection->getConnection($command);
  1504. $connectionObjectHash = spl_object_hash($cmdConnection);
  1505. if (isset($connectionExceptions[$connectionObjectHash])) {
  1506. $values[] = $connectionExceptions[$connectionObjectHash];
  1507. continue;
  1508. }
  1509. try {
  1510. $response = $cmdConnection->readResponse($command);
  1511. $values[] = ($response instanceof \Iterator
  1512. ? iterator_to_array($response)
  1513. : $response
  1514. );
  1515. }
  1516. catch (\Predis\ServerException $exception) {
  1517. $values[] = $exception->toResponseError();
  1518. }
  1519. catch (\Predis\CommunicationException $exception) {
  1520. $values[] = $exception;
  1521. $connectionExceptions[$connectionObjectHash] = $exception;
  1522. }
  1523. }
  1524. return $values;
  1525. }
  1526. }
  1527. /* ------------------------------------------------------------------------- */
  1528. namespace Predis\Distribution;
  1529. interface IDistributionStrategy {
  1530. public function add($node, $weight = null);
  1531. public function remove($node);
  1532. public function get($key);
  1533. public function generateKey($value);
  1534. }
  1535. class EmptyRingException extends \Exception { }
  1536. class HashRing implements IDistributionStrategy {
  1537. const DEFAULT_REPLICAS = 128;
  1538. const DEFAULT_WEIGHT = 100;
  1539. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1540. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1541. $this->_replicas = $replicas;
  1542. $this->_nodes = array();
  1543. }
  1544. public function add($node, $weight = null) {
  1545. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1546. // last wins, thus the order in which nodes are added is significant.
  1547. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  1548. $this->reset();
  1549. }
  1550. public function remove($node) {
  1551. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1552. // scratch, in order to reassign possible hashes with collisions to the
  1553. // right node according to the order in which they were added in the
  1554. // first place.
  1555. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1556. if ($this->_nodes[$i]['object'] === $node) {
  1557. array_splice($this->_nodes, $i, 1);
  1558. $this->reset();
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. private function reset() {
  1564. unset($this->_ring);
  1565. unset($this->_ringKeys);
  1566. unset($this->_ringKeysCount);
  1567. }
  1568. private function isInitialized() {
  1569. return isset($this->_ringKeys);
  1570. }
  1571. private function computeTotalWeight() {
  1572. // TODO: array_reduce + lambda for PHP 5.3
  1573. $totalWeight = 0;
  1574. foreach ($this->_nodes as $node) {
  1575. $totalWeight += $node['weight'];
  1576. }
  1577. return $totalWeight;
  1578. }
  1579. private function initialize() {
  1580. if ($this->isInitialized()) {
  1581. return;
  1582. }
  1583. if (count($this->_nodes) === 0) {
  1584. throw new EmptyRingException('Cannot initialize empty hashring');
  1585. }
  1586. $this->_ring = array();
  1587. $totalWeight = $this->computeTotalWeight();
  1588. $nodesCount = count($this->_nodes);
  1589. foreach ($this->_nodes as $node) {
  1590. $weightRatio = $node['weight'] / $totalWeight;
  1591. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1592. }
  1593. ksort($this->_ring, SORT_NUMERIC);
  1594. $this->_ringKeys = array_keys($this->_ring);
  1595. $this->_ringKeysCount = count($this->_ringKeys);
  1596. }
  1597. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1598. $nodeObject = $node['object'];
  1599. $nodeHash = (string) $nodeObject;
  1600. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1601. for ($i = 0; $i < $replicas; $i++) {
  1602. $key = crc32("$nodeHash:$i");
  1603. $ring[$key] = $nodeObject;
  1604. }
  1605. }
  1606. public function generateKey($value) {
  1607. return crc32($value);
  1608. }
  1609. public function get($key) {
  1610. return $this->_ring[$this->getNodeKey($key)];
  1611. }
  1612. private function getNodeKey($key) {
  1613. $this->initialize();
  1614. $ringKeys = $this->_ringKeys;
  1615. $upper = $this->_ringKeysCount - 1;
  1616. $lower = 0;
  1617. while ($lower <= $upper) {
  1618. $index = ($lower + $upper) >> 1;
  1619. $item = $ringKeys[$index];
  1620. if ($item > $key) {
  1621. $upper = $index - 1;
  1622. }
  1623. else if ($item < $key) {
  1624. $lower = $index + 1;
  1625. }
  1626. else {
  1627. return $item;
  1628. }
  1629. }
  1630. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1631. }
  1632. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1633. // NOTE: binary search for the last item in _ringkeys with a value
  1634. // less or equal to the key. If no such item exists, return the
  1635. // last item.
  1636. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1637. }
  1638. }
  1639. class KetamaPureRing extends HashRing {
  1640. const DEFAULT_REPLICAS = 160;
  1641. public function __construct() {
  1642. parent::__construct($this::DEFAULT_REPLICAS);
  1643. }
  1644. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1645. $nodeObject = $node['object'];
  1646. $nodeHash = (string) $nodeObject;
  1647. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1648. for ($i = 0; $i < $replicas; $i++) {
  1649. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1650. foreach ($unpackedDigest as $key) {
  1651. $ring[$key] = $nodeObject;
  1652. }
  1653. }
  1654. }
  1655. public function generateKey($value) {
  1656. $hash = unpack('V', md5($value, true));
  1657. return $hash[1];
  1658. }
  1659. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1660. // NOTE: binary search for the first item in _ringkeys with a value
  1661. // greater or equal to the key. If no such item exists, return the
  1662. // first item.
  1663. return $lower < $ringKeysCount ? $lower : 0;
  1664. }
  1665. }
  1666. /* ------------------------------------------------------------------------- */
  1667. namespace Predis\Shared;
  1668. class Utils {
  1669. public static function onCommunicationException(\Predis\CommunicationException $exception) {
  1670. if ($exception->shouldResetConnection()) {
  1671. $connection = $exception->getConnection();
  1672. if ($connection->isConnected()) {
  1673. $connection->disconnect();
  1674. }
  1675. }
  1676. throw $exception;
  1677. }
  1678. }
  1679. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1680. protected $_position, $_current, $_replySize;
  1681. public function rewind() {
  1682. // NOOP
  1683. }
  1684. public function current() {
  1685. return $this->_current;
  1686. }
  1687. public function key() {
  1688. return $this->_position;
  1689. }
  1690. public function next() {
  1691. if (++$this->_position < $this->_replySize) {
  1692. $this->_current = $this->getValue();
  1693. }
  1694. return $this->_position;
  1695. }
  1696. public function valid() {
  1697. return $this->_position < $this->_replySize;
  1698. }
  1699. public function count() {
  1700. // NOTE: use count if you want to get the size of the current multi-bulk
  1701. // response without using iterator_count (which actually consumes
  1702. // our iterator to calculate the size, and we cannot perform a rewind)
  1703. return $this->_replySize;
  1704. }
  1705. protected abstract function getValue();
  1706. }
  1707. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1708. private $_connection;
  1709. public function __construct(\Predis\Connection $connection, $size) {
  1710. $this->_connection = $connection;
  1711. $this->_reader = $connection->getResponseReader();
  1712. $this->_position = 0;
  1713. $this->_current = $size > 0 ? $this->getValue() : null;
  1714. $this->_replySize = $size;
  1715. }
  1716. public function __destruct() {
  1717. // when the iterator is garbage-collected (e.g. it goes out of the
  1718. // scope of a foreach) but it has not reached its end, we must sync
  1719. // the client with the queued elements that have not been read from
  1720. // the connection with the server.
  1721. $this->sync();
  1722. }
  1723. public function sync($drop = false) {
  1724. if ($drop == true) {
  1725. if ($this->valid()) {
  1726. $this->_position = $this->_replySize;
  1727. $this->_connection->disconnect();
  1728. }
  1729. }
  1730. else {
  1731. while ($this->valid()) {
  1732. $this->next();
  1733. }
  1734. }
  1735. }
  1736. protected function getValue() {
  1737. return $this->_reader->read($this->_connection);
  1738. }
  1739. }
  1740. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1741. private $_iterator;
  1742. public function __construct(MultiBulkResponseIterator $iterator) {
  1743. $virtualSize = count($iterator) / 2;
  1744. $this->_iterator = $iterator;
  1745. $this->_position = 0;
  1746. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1747. $this->_replySize = $virtualSize;
  1748. }
  1749. public function __destruct() {
  1750. $this->_iterator->sync();
  1751. }
  1752. protected function getValue() {
  1753. $k = $this->_iterator->current();
  1754. $this->_iterator->next();
  1755. $v = $this->_iterator->current();
  1756. $this->_iterator->next();
  1757. return array($k, $v);
  1758. }
  1759. }
  1760. /* ------------------------------------------------------------------------- */
  1761. namespace Predis\Commands;
  1762. /* miscellaneous commands */
  1763. class Ping extends \Predis\MultiBulkCommand {
  1764. public function canBeHashed() { return false; }
  1765. public function getCommandId() { return 'PING'; }
  1766. public function parseResponse($data) {
  1767. return $data === 'PONG' ? true : false;
  1768. }
  1769. }
  1770. class DoEcho extends \Predis\MultiBulkCommand {
  1771. public function canBeHashed() { return false; }
  1772. public function getCommandId() { return 'ECHO'; }
  1773. }
  1774. class Auth extends \Predis\MultiBulkCommand {
  1775. public function canBeHashed() { return false; }
  1776. public function getCommandId() { return 'AUTH'; }
  1777. }
  1778. /* connection handling */
  1779. class Quit extends \Predis\MultiBulkCommand {
  1780. public function canBeHashed() { return false; }
  1781. public function getCommandId() { return 'QUIT'; }
  1782. public function closesConnection() { return true; }
  1783. }
  1784. /* commands operating on string values */
  1785. class Set extends \Predis\MultiBulkCommand {
  1786. public function getCommandId() { return 'SET'; }
  1787. }
  1788. class SetExpire extends \Predis\MultiBulkCommand {
  1789. public function getCommandId() { return 'SETEX'; }
  1790. }
  1791. class SetPreserve extends \Predis\MultiBulkCommand {
  1792. public function getCommandId() { return 'SETNX'; }
  1793. public function parseResponse($data) { return (bool) $data; }
  1794. }
  1795. class SetMultiple extends \Predis\MultiBulkCommand {
  1796. public function canBeHashed() { return false; }
  1797. public function getCommandId() { return 'MSET'; }
  1798. public function filterArguments(Array $arguments) {
  1799. if (count($arguments) === 1 && is_array($arguments[0])) {
  1800. $flattenedKVs = array();
  1801. $args = &$arguments[0];
  1802. foreach ($args as $k => $v) {
  1803. $flattenedKVs[] = $k;
  1804. $flattenedKVs[] = $v;
  1805. }
  1806. return $flattenedKVs;
  1807. }
  1808. return $arguments;
  1809. }
  1810. }
  1811. class SetMultiplePreserve extends \Predis\Commands\SetMultiple {
  1812. public function canBeHashed() { return false; }
  1813. public function getCommandId() { return 'MSETNX'; }
  1814. public function parseResponse($data) { return (bool) $data; }
  1815. }
  1816. class Get extends \Predis\MultiBulkCommand {
  1817. public function getCommandId() { return 'GET'; }
  1818. }
  1819. class GetMultiple extends \Predis\MultiBulkCommand {
  1820. public function canBeHashed() { return false; }
  1821. public function getCommandId() { return 'MGET'; }
  1822. }
  1823. class GetSet extends \Predis\MultiBulkCommand {
  1824. public function getCommandId() { return 'GETSET'; }
  1825. }
  1826. class Increment extends \Predis\MultiBulkCommand {
  1827. public function getCommandId() { return 'INCR'; }
  1828. }
  1829. class IncrementBy extends \Predis\MultiBulkCommand {
  1830. public function getCommandId() { return 'INCRBY'; }
  1831. }
  1832. class Decrement extends \Predis\MultiBulkCommand {
  1833. public function getCommandId() { return 'DECR'; }
  1834. }
  1835. class DecrementBy extends \Predis\MultiBulkCommand {
  1836. public function getCommandId() { return 'DECRBY'; }
  1837. }
  1838. class Exists extends \Predis\MultiBulkCommand {
  1839. public function getCommandId() { return 'EXISTS'; }
  1840. public function parseResponse($data) { return (bool) $data; }
  1841. }
  1842. class Delete extends \Predis\MultiBulkCommand {
  1843. public function getCommandId() { return 'DEL'; }
  1844. }
  1845. class Type extends \Predis\MultiBulkCommand {
  1846. public function getCommandId() { return 'TYPE'; }
  1847. }
  1848. class Append extends \Predis\MultiBulkCommand {
  1849. public function getCommandId() { return 'APPEND'; }
  1850. }
  1851. class Substr extends \Predis\MultiBulkCommand {
  1852. public function getCommandId() { return 'SUBSTR'; }
  1853. }
  1854. /* commands operating on the key space */
  1855. class Keys extends \Predis\MultiBulkCommand {
  1856. public function canBeHashed() { return false; }
  1857. public function getCommandId() { return 'KEYS'; }
  1858. public function parseResponse($data) {
  1859. // TODO: is this behaviour correct?
  1860. if (is_array($data) || $data instanceof \Iterator) {
  1861. return $data;
  1862. }
  1863. return strlen($data) > 0 ? explode(' ', $data) : array();
  1864. }
  1865. }
  1866. class RandomKey extends \Predis\MultiBulkCommand {
  1867. public function canBeHashed() { return false; }
  1868. public function getCommandId() { return 'RANDOMKEY'; }
  1869. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1870. }
  1871. class Rename extends \Predis\MultiBulkCommand {
  1872. public function canBeHashed() { return false; }
  1873. public function getCommandId() { return 'RENAME'; }
  1874. }
  1875. class RenamePreserve extends \Predis\MultiBulkCommand {
  1876. public function canBeHashed() { return false; }
  1877. public function getCommandId() { return 'RENAMENX'; }
  1878. public function parseResponse($data) { return (bool) $data; }
  1879. }
  1880. class Expire extends \Predis\MultiBulkCommand {
  1881. public function getCommandId() { return 'EXPIRE'; }
  1882. public function parseResponse($data) { return (bool) $data; }
  1883. }
  1884. class ExpireAt extends \Predis\MultiBulkCommand {
  1885. public function getCommandId() { return 'EXPIREAT'; }
  1886. public function parseResponse($data) { return (bool) $data; }
  1887. }
  1888. class DatabaseSize extends \Predis\MultiBulkCommand {
  1889. public function canBeHashed() { return false; }
  1890. public function getCommandId() { return 'DBSIZE'; }
  1891. }
  1892. class TimeToLive extends \Predis\MultiBulkCommand {
  1893. public function getCommandId() { return 'TTL'; }
  1894. }
  1895. /* commands operating on lists */
  1896. class ListPushTail extends \Predis\MultiBulkCommand {
  1897. public function getCommandId() { return 'RPUSH'; }
  1898. }
  1899. class ListPushHead extends \Predis\MultiBulkCommand {
  1900. public function getCommandId() { return 'LPUSH'; }
  1901. }
  1902. class ListLength extends \Predis\MultiBulkCommand {
  1903. public function getCommandId() { return 'LLEN'; }
  1904. }
  1905. class ListRange extends \Predis\MultiBulkCommand {
  1906. public function getCommandId() { return 'LRANGE'; }
  1907. }
  1908. class ListTrim extends \Predis\MultiBulkCommand {
  1909. public function getCommandId() { return 'LTRIM'; }
  1910. }
  1911. class ListIndex extends \Predis\MultiBulkCommand {
  1912. public function getCommandId() { return 'LINDEX'; }
  1913. }
  1914. class ListSet extends \Predis\MultiBulkCommand {
  1915. public function getCommandId() { return 'LSET'; }
  1916. }
  1917. class ListRemove extends \Predis\MultiBulkCommand {
  1918. public function getCommandId() { return 'LREM'; }
  1919. }
  1920. class ListPopLastPushHead extends \Predis\MultiBulkCommand {
  1921. public function getCommandId() { return 'RPOPLPUSH'; }
  1922. }
  1923. class ListPopLastPushHeadBulk extends \Predis\MultiBulkCommand {
  1924. public function getCommandId() { return 'RPOPLPUSH'; }
  1925. }
  1926. class ListPopFirst extends \Predis\MultiBulkCommand {
  1927. public function getCommandId() { return 'LPOP'; }
  1928. }
  1929. class ListPopLast extends \Predis\MultiBulkCommand {
  1930. public function getCommandId() { return 'RPOP'; }
  1931. }
  1932. class ListPopFirstBlocking extends \Predis\MultiBulkCommand {
  1933. public function getCommandId() { return 'BLPOP'; }
  1934. }
  1935. class ListPopLastBlocking extends \Predis\MultiBulkCommand {
  1936. public function getCommandId() { return 'BRPOP'; }
  1937. }
  1938. /* commands operating on sets */
  1939. class SetAdd extends \Predis\MultiBulkCommand {
  1940. public function getCommandId() { return 'SADD'; }
  1941. public function parseResponse($data) { return (bool) $data; }
  1942. }
  1943. class SetRemove extends \Predis\MultiBulkCommand {
  1944. public function getCommandId() { return 'SREM'; }
  1945. public function parseResponse($data) { return (bool) $data; }
  1946. }
  1947. class SetPop extends \Predis\MultiBulkCommand {
  1948. public function getCommandId() { return 'SPOP'; }
  1949. }
  1950. class SetMove extends \Predis\MultiBulkCommand {
  1951. public function canBeHashed() { return false; }
  1952. public function getCommandId() { return 'SMOVE'; }
  1953. public function parseResponse($data) { return (bool) $data; }
  1954. }
  1955. class SetCardinality extends \Predis\MultiBulkCommand {
  1956. public function getCommandId() { return 'SCARD'; }
  1957. }
  1958. class SetIsMember extends \Predis\MultiBulkCommand {
  1959. public function getCommandId() { return 'SISMEMBER'; }
  1960. public function parseResponse($data) { return (bool) $data; }
  1961. }
  1962. class SetIntersection extends \Predis\MultiBulkCommand {
  1963. public function getCommandId() { return 'SINTER'; }
  1964. }
  1965. class SetIntersectionStore extends \Predis\MultiBulkCommand {
  1966. public function getCommandId() { return 'SINTERSTORE'; }
  1967. }
  1968. class SetUnion extends \Predis\MultiBulkCommand {
  1969. public function getCommandId() { return 'SUNION'; }
  1970. }
  1971. class SetUnionStore extends \Predis\MultiBulkCommand {
  1972. public function getCommandId() { return 'SUNIONSTORE'; }
  1973. }
  1974. class SetDifference extends \Predis\MultiBulkCommand {
  1975. public function getCommandId() { return 'SDIFF'; }
  1976. }
  1977. class SetDifferenceStore extends \Predis\MultiBulkCommand {
  1978. public function getCommandId() { return 'SDIFFSTORE'; }
  1979. }
  1980. class SetMembers extends \Predis\MultiBulkCommand {
  1981. public function getCommandId() { return 'SMEMBERS'; }
  1982. }
  1983. class SetRandomMember extends \Predis\MultiBulkCommand {
  1984. public function getCommandId() { return 'SRANDMEMBER'; }
  1985. }
  1986. /* commands operating on sorted sets */
  1987. class ZSetAdd extends \Predis\MultiBulkCommand {
  1988. public function getCommandId() { return 'ZADD'; }
  1989. public function parseResponse($data) { return (bool) $data; }
  1990. }
  1991. class ZSetIncrementBy extends \Predis\MultiBulkCommand {
  1992. public function getCommandId() { return 'ZINCRBY'; }
  1993. }
  1994. class ZSetRemove extends \Predis\MultiBulkCommand {
  1995. public function getCommandId() { return 'ZREM'; }
  1996. public function parseResponse($data) { return (bool) $data; }
  1997. }
  1998. class ZSetUnionStore extends \Predis\MultiBulkCommand {
  1999. public function getCommandId() { return 'ZUNIONSTORE'; }
  2000. public function filterArguments(Array $arguments) {
  2001. $options = array();
  2002. $argc = count($arguments);
  2003. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  2004. $options = $this->prepareOptions(array_pop($arguments));
  2005. }
  2006. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  2007. return array_merge($args, $options);
  2008. }
  2009. private function prepareOptions($options) {
  2010. $opts = array_change_key_case($options, CASE_UPPER);
  2011. $finalizedOpts = array();
  2012. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2013. $finalizedOpts[] = 'WEIGHTS';
  2014. $finalizedOpts[] = $opts['WEIGHTS'][0];
  2015. $finalizedOpts[] = $opts['WEIGHTS'][1];
  2016. }
  2017. if (isset($opts['AGGREGATE'])) {
  2018. $finalizedOpts[] = 'AGGREGATE';
  2019. $finalizedOpts[] = $opts['AGGREGATE'];
  2020. }
  2021. return $finalizedOpts;
  2022. }
  2023. }
  2024. class ZSetIntersectionStore extends \Predis\Commands\ZSetUnionStore {
  2025. public function getCommandId() { return 'ZINTERSTORE'; }
  2026. }
  2027. class ZSetRange extends \Predis\MultiBulkCommand {
  2028. public function getCommandId() { return 'ZRANGE'; }
  2029. public function parseResponse($data) {
  2030. $arguments = $this->getArguments();
  2031. if (count($arguments) === 4) {
  2032. if (strtolower($arguments[3]) === 'withscores') {
  2033. if ($data instanceof \Iterator) {
  2034. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2035. }
  2036. $result = array();
  2037. for ($i = 0; $i < count($data); $i++) {
  2038. $result[] = array($data[$i], $data[++$i]);
  2039. }
  2040. return $result;
  2041. }
  2042. }
  2043. return $data;
  2044. }
  2045. }
  2046. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  2047. public function getCommandId() { return 'ZREVRANGE'; }
  2048. }
  2049. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  2050. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2051. }
  2052. class ZSetCount extends \Predis\MultiBulkCommand {
  2053. public function getCommandId() { return 'ZCOUNT'; }
  2054. }
  2055. class ZSetCardinality extends \Predis\MultiBulkCommand {
  2056. public function getCommandId() { return 'ZCARD'; }
  2057. }
  2058. class ZSetScore extends \Predis\MultiBulkCommand {
  2059. public function getCommandId() { return 'ZSCORE'; }
  2060. }
  2061. class ZSetRemoveRangeByScore extends \Predis\MultiBulkCommand {
  2062. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2063. }
  2064. class ZSetRank extends \Predis\MultiBulkCommand {
  2065. public function getCommandId() { return 'ZRANK'; }
  2066. }
  2067. class ZSetReverseRank extends \Predis\MultiBulkCommand {
  2068. public function getCommandId() { return 'ZREVRANK'; }
  2069. }
  2070. class ZSetRemoveRangeByRank extends \Predis\MultiBulkCommand {
  2071. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2072. }
  2073. /* commands operating on hashes */
  2074. class HashSet extends \Predis\MultiBulkCommand {
  2075. public function getCommandId() { return 'HSET'; }
  2076. public function parseResponse($data) { return (bool) $data; }
  2077. }
  2078. class HashSetPreserve extends \Predis\MultiBulkCommand {
  2079. public function getCommandId() { return 'HSETNX'; }
  2080. public function parseResponse($data) { return (bool) $data; }
  2081. }
  2082. class HashSetMultiple extends \Predis\MultiBulkCommand {
  2083. public function getCommandId() { return 'HMSET'; }
  2084. public function filterArguments(Array $arguments) {
  2085. if (count($arguments) === 2 && is_array($arguments[1])) {
  2086. $flattenedKVs = array($arguments[0]);
  2087. $args = &$arguments[1];
  2088. foreach ($args as $k => $v) {
  2089. $flattenedKVs[] = $k;
  2090. $flattenedKVs[] = $v;
  2091. }
  2092. return $flattenedKVs;
  2093. }
  2094. return $arguments;
  2095. }
  2096. }
  2097. class HashIncrementBy extends \Predis\MultiBulkCommand {
  2098. public function getCommandId() { return 'HINCRBY'; }
  2099. }
  2100. class HashGet extends \Predis\MultiBulkCommand {
  2101. public function getCommandId() { return 'HGET'; }
  2102. }
  2103. class HashGetMultiple extends \Predis\MultiBulkCommand {
  2104. public function getCommandId() { return 'HMGET'; }
  2105. public function filterArguments(Array $arguments) {
  2106. if (count($arguments) === 2 && is_array($arguments[1])) {
  2107. $flattenedKVs = array($arguments[0]);
  2108. $args = &$arguments[1];
  2109. foreach ($args as $v) {
  2110. $flattenedKVs[] = $v;
  2111. }
  2112. return $flattenedKVs;
  2113. }
  2114. return $arguments;
  2115. }
  2116. }
  2117. class HashDelete extends \Predis\MultiBulkCommand {
  2118. public function getCommandId() { return 'HDEL'; }
  2119. public function parseResponse($data) { return (bool) $data; }
  2120. }
  2121. class HashExists extends \Predis\MultiBulkCommand {
  2122. public function getCommandId() { return 'HEXISTS'; }
  2123. public function parseResponse($data) { return (bool) $data; }
  2124. }
  2125. class HashLength extends \Predis\MultiBulkCommand {
  2126. public function getCommandId() { return 'HLEN'; }
  2127. }
  2128. class HashKeys extends \Predis\MultiBulkCommand {
  2129. public function getCommandId() { return 'HKEYS'; }
  2130. }
  2131. class HashValues extends \Predis\MultiBulkCommand {
  2132. public function getCommandId() { return 'HVALS'; }
  2133. }
  2134. class HashGetAll extends \Predis\MultiBulkCommand {
  2135. public function getCommandId() { return 'HGETALL'; }
  2136. public function parseResponse($data) {
  2137. if ($data instanceof \Iterator) {
  2138. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2139. }
  2140. $result = array();
  2141. for ($i = 0; $i < count($data); $i++) {
  2142. $result[$data[$i]] = $data[++$i];
  2143. }
  2144. return $result;
  2145. }
  2146. }
  2147. /* multiple databases handling commands */
  2148. class SelectDatabase extends \Predis\MultiBulkCommand {
  2149. public function canBeHashed() { return false; }
  2150. public function getCommandId() { return 'SELECT'; }
  2151. }
  2152. class MoveKey extends \Predis\MultiBulkCommand {
  2153. public function canBeHashed() { return false; }
  2154. public function getCommandId() { return 'MOVE'; }
  2155. public function parseResponse($data) { return (bool) $data; }
  2156. }
  2157. class FlushDatabase extends \Predis\MultiBulkCommand {
  2158. public function canBeHashed() { return false; }
  2159. public function getCommandId() { return 'FLUSHDB'; }
  2160. }
  2161. class FlushAll extends \Predis\MultiBulkCommand {
  2162. public function canBeHashed() { return false; }
  2163. public function getCommandId() { return 'FLUSHALL'; }
  2164. }
  2165. /* sorting */
  2166. class Sort extends \Predis\MultiBulkCommand {
  2167. public function getCommandId() { return 'SORT'; }
  2168. public function filterArguments(Array $arguments) {
  2169. if (count($arguments) === 1) {
  2170. return $arguments;
  2171. }
  2172. // TODO: add more parameters checks
  2173. $query = array($arguments[0]);
  2174. $sortParams = $arguments[1];
  2175. if (isset($sortParams['by'])) {
  2176. $query[] = 'BY';
  2177. $query[] = $sortParams['by'];
  2178. }
  2179. if (isset($sortParams['get'])) {
  2180. $getargs = $sortParams['get'];
  2181. if (is_array($getargs)) {
  2182. foreach ($getargs as $getarg) {
  2183. $query[] = 'GET';
  2184. $query[] = $getarg;
  2185. }
  2186. }
  2187. else {
  2188. $query[] = 'GET';
  2189. $query[] = $getargs;
  2190. }
  2191. }
  2192. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  2193. $query[] = 'LIMIT';
  2194. $query[] = $sortParams['limit'][0];
  2195. $query[] = $sortParams['limit'][1];
  2196. }
  2197. if (isset($sortParams['sort'])) {
  2198. $query[] = strtoupper($sortParams['sort']);
  2199. }
  2200. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  2201. $query[] = 'ALPHA';
  2202. }
  2203. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  2204. $query[] = 'STORE';
  2205. $query[] = $sortParams['store'];
  2206. }
  2207. return $query;
  2208. }
  2209. }
  2210. /* transactions */
  2211. class Multi extends \Predis\MultiBulkCommand {
  2212. public function canBeHashed() { return false; }
  2213. public function getCommandId() { return 'MULTI'; }
  2214. }
  2215. class Exec extends \Predis\MultiBulkCommand {
  2216. public function canBeHashed() { return false; }
  2217. public function getCommandId() { return 'EXEC'; }
  2218. }
  2219. class Discard extends \Predis\MultiBulkCommand {
  2220. public function canBeHashed() { return false; }
  2221. public function getCommandId() { return 'DISCARD'; }
  2222. }
  2223. /* publish/subscribe */
  2224. class Subscribe extends \Predis\MultiBulkCommand {
  2225. public function canBeHashed() { return false; }
  2226. public function getCommandId() { return 'SUBSCRIBE'; }
  2227. }
  2228. class Unsubscribe extends \Predis\MultiBulkCommand {
  2229. public function canBeHashed() { return false; }
  2230. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2231. }
  2232. class SubscribeByPattern extends \Predis\MultiBulkCommand {
  2233. public function canBeHashed() { return false; }
  2234. public function getCommandId() { return 'PSUBSCRIBE'; }
  2235. }
  2236. class UnsubscribeByPattern extends \Predis\MultiBulkCommand {
  2237. public function canBeHashed() { return false; }
  2238. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2239. }
  2240. class Publish extends \Predis\MultiBulkCommand {
  2241. public function canBeHashed() { return false; }
  2242. public function getCommandId() { return 'PUBLISH'; }
  2243. }
  2244. class Watch extends \Predis\MultiBulkCommand {
  2245. public function canBeHashed() { return false; }
  2246. public function getCommandId() { return 'WATCH'; }
  2247. }
  2248. class Unwatch extends \Predis\MultiBulkCommand {
  2249. public function canBeHashed() { return false; }
  2250. public function getCommandId() { return 'UNWATCH'; }
  2251. }
  2252. /* persistence control commands */
  2253. class Save extends \Predis\MultiBulkCommand {
  2254. public function canBeHashed() { return false; }
  2255. public function getCommandId() { return 'SAVE'; }
  2256. }
  2257. class BackgroundSave extends \Predis\MultiBulkCommand {
  2258. public function canBeHashed() { return false; }
  2259. public function getCommandId() { return 'BGSAVE'; }
  2260. public function parseResponse($data) {
  2261. if ($data == 'Background saving started') {
  2262. return true;
  2263. }
  2264. return $data;
  2265. }
  2266. }
  2267. class BackgroundRewriteAppendOnlyFile extends \Predis\MultiBulkCommand {
  2268. public function canBeHashed() { return false; }
  2269. public function getCommandId() { return 'BGREWRITEAOF'; }
  2270. public function parseResponse($data) {
  2271. return $data == 'Background append only file rewriting started';
  2272. }
  2273. }
  2274. class LastSave extends \Predis\MultiBulkCommand {
  2275. public function canBeHashed() { return false; }
  2276. public function getCommandId() { return 'LASTSAVE'; }
  2277. }
  2278. class Shutdown extends \Predis\MultiBulkCommand {
  2279. public function canBeHashed() { return false; }
  2280. public function getCommandId() { return 'SHUTDOWN'; }
  2281. public function closesConnection() { return true; }
  2282. }
  2283. /* remote server control commands */
  2284. class Info extends \Predis\MultiBulkCommand {
  2285. public function canBeHashed() { return false; }
  2286. public function getCommandId() { return 'INFO'; }
  2287. public function parseResponse($data) {
  2288. $info = array();
  2289. $infoLines = explode("\r\n", $data, -1);
  2290. foreach ($infoLines as $row) {
  2291. list($k, $v) = explode(':', $row);
  2292. if (!preg_match('/^db\d+$/', $k)) {
  2293. $info[$k] = $v;
  2294. }
  2295. else {
  2296. $db = array();
  2297. foreach (explode(',', $v) as $dbvar) {
  2298. list($dbvk, $dbvv) = explode('=', $dbvar);
  2299. $db[trim($dbvk)] = $dbvv;
  2300. }
  2301. $info[$k] = $db;
  2302. }
  2303. }
  2304. return $info;
  2305. }
  2306. }
  2307. class SlaveOf extends \Predis\MultiBulkCommand {
  2308. public function canBeHashed() { return false; }
  2309. public function getCommandId() { return 'SLAVEOF'; }
  2310. public function filterArguments(Array $arguments) {
  2311. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2312. return array('NO', 'ONE');
  2313. }
  2314. return $arguments;
  2315. }
  2316. }
  2317. class Config extends \Predis\MultiBulkCommand {
  2318. public function canBeHashed() { return false; }
  2319. public function getCommandId() { return 'CONFIG'; }
  2320. }
  2321. ?>