Predis.php 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { } // Client-side errors
  5. class AbortedMultiExec extends PredisException { } // Aborted multi/exec
  6. class ServerException extends PredisException { // Server-side errors
  7. public function toResponseError() {
  8. return new ResponseError($this->getMessage());
  9. }
  10. }
  11. class CommunicationException extends PredisException { // Communication errors
  12. private $_connection;
  13. public function __construct(Connection $connection, $message = null, $code = null) {
  14. $this->_connection = $connection;
  15. parent::__construct($message, $code);
  16. }
  17. public function getConnection() { return $this->_connection; }
  18. public function shouldResetConnection() { return true; }
  19. }
  20. class MalformedServerResponse extends CommunicationException { } // Unexpected responses
  21. /* ------------------------------------------------------------------------- */
  22. class Client {
  23. const VERSION = '0.6.6';
  24. private $_options, $_connection, $_serverProfile, $_responseReader;
  25. public function __construct($parameters = null, $clientOptions = null) {
  26. $this->setupClient($clientOptions ?: new ClientOptions());
  27. $this->setupConnection($parameters);
  28. }
  29. public static function create(/* arguments */) {
  30. $argv = func_get_args();
  31. $argc = func_num_args();
  32. $options = null;
  33. $lastArg = $argv[$argc-1];
  34. if ($argc > 0 && !is_string($lastArg) && ($lastArg instanceof ClientOptions ||
  35. is_subclass_of($lastArg, '\Predis\RedisServerProfile'))) {
  36. $options = array_pop($argv);
  37. $argc--;
  38. }
  39. if ($argc === 0) {
  40. throw new ClientException('Missing connection parameters');
  41. }
  42. return new Client($argc === 1 ? $argv[0] : $argv, $options);
  43. }
  44. private static function filterClientOptions($options) {
  45. if ($options instanceof ClientOptions) {
  46. return $options;
  47. }
  48. if (is_array($options)) {
  49. return new ClientOptions($options);
  50. }
  51. if ($options instanceof RedisServerProfile) {
  52. return new ClientOptions(array(
  53. 'profile' => $options
  54. ));
  55. }
  56. if (is_string($options)) {
  57. return new ClientOptions(array(
  58. 'profile' => RedisServerProfile::get($options)
  59. ));
  60. }
  61. throw new \InvalidArgumentException("Invalid type for client options");
  62. }
  63. private function setupClient($options) {
  64. $options = self::filterClientOptions($options);
  65. $this->setProfile($options->profile);
  66. $reader = $options->reader;
  67. $reader->setOption('iterable_multibulk', $options->iterable_multibulk);
  68. $reader->setOption('throw_on_error', $options->throw_on_error);
  69. $this->_options = $options;
  70. $this->_responseReader = $reader;
  71. }
  72. private function setupConnection($parameters) {
  73. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  74. throw new ClientException('Invalid parameters type (array or string expected)');
  75. }
  76. if (is_array($parameters) && isset($parameters[0])) {
  77. $cluster = new ConnectionCluster($this->_options->key_distribution);
  78. foreach ($parameters as $shardParams) {
  79. $cluster->add($this->createConnection($shardParams));
  80. }
  81. $this->setConnection($cluster);
  82. }
  83. else {
  84. $this->setConnection($this->createConnection($parameters));
  85. }
  86. }
  87. private function createConnection($parameters) {
  88. if (!$parameters instanceof ConnectionParameters) {
  89. $parameters = new ConnectionParameters($parameters);
  90. }
  91. $connection = new Connection($parameters, $this->_responseReader);
  92. if ($parameters->password !== null) {
  93. $connection->pushInitCommand($this->createCommand(
  94. 'auth', array($parameters->password)
  95. ));
  96. }
  97. if ($parameters->database !== null) {
  98. $connection->pushInitCommand($this->createCommand(
  99. 'select', array($parameters->database)
  100. ));
  101. }
  102. return $connection;
  103. }
  104. private function setConnection(IConnection $connection) {
  105. $this->_connection = $connection;
  106. }
  107. public function setProfile($serverProfile) {
  108. if ($serverProfile instanceof RedisServerProfile) {
  109. $this->_serverProfile = $serverProfile;
  110. }
  111. else if (is_string($serverProfile)) {
  112. $this->_serverProfile = RedisServerProfile::get($serverProfile);
  113. }
  114. else {
  115. throw new \InvalidArgumentException(
  116. "Invalid type for server profile, \Predis\RedisServerProfile or string expected"
  117. );
  118. }
  119. }
  120. public function getProfile() {
  121. return $this->_serverProfile;
  122. }
  123. public function getResponseReader() {
  124. return $this->_responseReader;
  125. }
  126. public function getClientFor($connectionAlias) {
  127. if (!Shared\Utils::isCluster($this->_connection)) {
  128. throw new ClientException(
  129. 'This method is supported only when the client is connected to a cluster of connections'
  130. );
  131. }
  132. $connection = $this->_connection->getConnectionById($connectionAlias);
  133. if ($connection === null) {
  134. throw new \InvalidArgumentException(
  135. "Invalid connection alias: '$connectionAlias'"
  136. );
  137. }
  138. $newClient = new Client();
  139. $newClient->setupClient($this->_options);
  140. $newClient->setConnection($connection);
  141. return $newClient;
  142. }
  143. public function connect() {
  144. $this->_connection->connect();
  145. }
  146. public function disconnect() {
  147. $this->_connection->disconnect();
  148. }
  149. public function isConnected() {
  150. return $this->_connection->isConnected();
  151. }
  152. public function getConnection($id = null) {
  153. if (!isset($id)) {
  154. return $this->_connection;
  155. }
  156. else {
  157. return Shared\Utils::isCluster($this->_connection)
  158. ? $this->_connection->getConnectionById($id)
  159. : $this->_connection;
  160. }
  161. }
  162. public function __call($method, $arguments) {
  163. $command = $this->_serverProfile->createCommand($method, $arguments);
  164. return $this->_connection->executeCommand($command);
  165. }
  166. public function createCommand($method, $arguments = array()) {
  167. return $this->_serverProfile->createCommand($method, $arguments);
  168. }
  169. public function executeCommand(Command $command) {
  170. return $this->_connection->executeCommand($command);
  171. }
  172. public function executeCommandOnShards(Command $command) {
  173. $replies = array();
  174. if (Shared\Utils::isCluster($this->_connection)) {
  175. foreach($this->_connection as $connection) {
  176. $replies[] = $connection->executeCommand($command);
  177. }
  178. }
  179. else {
  180. $replies[] = $this->_connection->executeCommand($command);
  181. }
  182. return $replies;
  183. }
  184. public function rawCommand($rawCommandData, $closesConnection = false) {
  185. if (Shared\Utils::isCluster($this->_connection)) {
  186. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  187. }
  188. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  189. }
  190. private function sharedInitializer($argv, $initializer) {
  191. $argc = count($argv);
  192. if ($argc === 0) {
  193. return $this->$initializer();
  194. }
  195. else if ($argc === 1) {
  196. list($arg0) = $argv;
  197. return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
  198. }
  199. else if ($argc === 2) {
  200. list($arg0, $arg1) = $argv;
  201. return $this->$initializer($arg0, $arg1);
  202. }
  203. return $this->$initializer($this, $arguments);
  204. }
  205. public function pipeline(/* arguments */) {
  206. return $this->sharedInitializer(func_get_args(), 'initPipeline');
  207. }
  208. public function pipelineSafe($pipelineBlock = null) {
  209. return $this->initPipeline(array('safe' => true), $pipelineBlock);
  210. }
  211. private function initPipeline(Array $options = null, $pipelineBlock = null) {
  212. $pipeline = null;
  213. if (isset($options)) {
  214. if (isset($options['safe']) && $options['safe'] == true) {
  215. $connection = $this->getConnection();
  216. $pipeline = new CommandPipeline($this, $connection instanceof Connection
  217. ? new Pipeline\SafeExecutor($connection)
  218. : new Pipeline\SafeClusterExecutor($connection)
  219. );
  220. }
  221. else {
  222. $pipeline = new CommandPipeline($this);
  223. }
  224. }
  225. else {
  226. $pipeline = new CommandPipeline($this);
  227. }
  228. return $this->pipelineExecute($pipeline, $pipelineBlock);
  229. }
  230. private function pipelineExecute(CommandPipeline $pipeline, $block) {
  231. return $block !== null ? $pipeline->execute($block) : $pipeline;
  232. }
  233. public function multiExec(/* arguments */) {
  234. return $this->sharedInitializer(func_get_args(), 'initMultiExec');
  235. }
  236. private function initMultiExec(Array $options = null, $transBlock = null) {
  237. $multi = isset($options) ? new MultiExecBlock($this, $options) : new MultiExecBlock($this);
  238. return $transBlock !== null ? $multi->execute($transBlock) : $multi;
  239. }
  240. public function pubSubContext(Array $options = null) {
  241. return new PubSubContext($this, $options);
  242. }
  243. }
  244. /* ------------------------------------------------------------------------- */
  245. interface IClientOptionsHandler {
  246. public function validate($option, $value);
  247. public function getDefault();
  248. }
  249. class ClientOptionsProfile implements IClientOptionsHandler {
  250. public function validate($option, $value) {
  251. if ($value instanceof \Predis\RedisServerProfile) {
  252. return $value;
  253. }
  254. if (is_string($value)) {
  255. return \Predis\RedisServerProfile::get($value);
  256. }
  257. throw new \InvalidArgumentException("Invalid value for option $option");
  258. }
  259. public function getDefault() {
  260. return \Predis\RedisServerProfile::getDefault();
  261. }
  262. }
  263. class ClientOptionsKeyDistribution implements IClientOptionsHandler {
  264. public function validate($option, $value) {
  265. if ($value instanceof \Predis\Distribution\IDistributionStrategy) {
  266. return $value;
  267. }
  268. if (is_string($value)) {
  269. $valueReflection = new \ReflectionClass($value);
  270. if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
  271. return new $value;
  272. }
  273. }
  274. throw new \InvalidArgumentException("Invalid value for option $option");
  275. }
  276. public function getDefault() {
  277. return new \Predis\Distribution\HashRing();
  278. }
  279. }
  280. class ClientOptionsIterableMultiBulk implements IClientOptionsHandler {
  281. public function validate($option, $value) {
  282. return (bool) $value;
  283. }
  284. public function getDefault() {
  285. return false;
  286. }
  287. }
  288. class ClientOptionsThrowOnError implements IClientOptionsHandler {
  289. public function validate($option, $value) {
  290. return (bool) $value;
  291. }
  292. public function getDefault() {
  293. return true;
  294. }
  295. }
  296. class ClientOptionsReader implements IClientOptionsHandler {
  297. public function validate($option, $value) {
  298. if ($value instanceof \Predis\IResponseReader) {
  299. return $value;
  300. }
  301. if (is_string($value)) {
  302. if ($value === 'composable') {
  303. return new \Predis\ResponseReader();
  304. }
  305. $valueReflection = new \ReflectionClass($value);
  306. if ($valueReflection->isSubclassOf('\Predis\IResponseReader')) {
  307. return new $value;
  308. }
  309. }
  310. throw new \InvalidArgumentException("Invalid value for option $option");
  311. }
  312. public function getDefault() {
  313. return new \Predis\FastResponseReader();
  314. }
  315. }
  316. class ClientOptions {
  317. private static $_optionsHandlers;
  318. private $_options;
  319. public function __construct($options = null) {
  320. self::initializeOptionsHandlers();
  321. $this->initializeOptions($options ?: array());
  322. }
  323. private static function initializeOptionsHandlers() {
  324. if (!isset(self::$_optionsHandlers)) {
  325. self::$_optionsHandlers = self::getOptionsHandlers();
  326. }
  327. }
  328. private static function getOptionsHandlers() {
  329. return array(
  330. 'profile' => new \Predis\ClientOptionsProfile(),
  331. 'key_distribution' => new \Predis\ClientOptionsKeyDistribution(),
  332. 'iterable_multibulk' => new \Predis\ClientOptionsIterableMultiBulk(),
  333. 'throw_on_error' => new \Predis\ClientOptionsThrowOnError(),
  334. 'reader' => new \Predis\ClientOptionsReader(),
  335. );
  336. }
  337. private function initializeOptions($options) {
  338. foreach ($options as $option => $value) {
  339. if (isset(self::$_optionsHandlers[$option])) {
  340. $handler = self::$_optionsHandlers[$option];
  341. $this->_options[$option] = $handler->validate($option, $value);
  342. }
  343. }
  344. }
  345. public function __get($option) {
  346. if (!isset($this->_options[$option])) {
  347. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  348. $this->_options[$option] = $defaultValue;
  349. }
  350. return $this->_options[$option];
  351. }
  352. public function __isset($option) {
  353. return isset(self::$_optionsHandlers[$option]);
  354. }
  355. }
  356. /* ------------------------------------------------------------------------- */
  357. class Protocol {
  358. const NEWLINE = "\r\n";
  359. const OK = 'OK';
  360. const ERROR = 'ERR';
  361. const QUEUED = 'QUEUED';
  362. const NULL = 'nil';
  363. const PREFIX_STATUS = '+';
  364. const PREFIX_ERROR = '-';
  365. const PREFIX_INTEGER = ':';
  366. const PREFIX_BULK = '$';
  367. const PREFIX_MULTI_BULK = '*';
  368. }
  369. abstract class Command {
  370. private $_hash;
  371. private $_arguments = array();
  372. public abstract function getCommandId();
  373. public abstract function serializeRequest($command, $arguments);
  374. public function canBeHashed() {
  375. return true;
  376. }
  377. public function getHash(Distribution\IDistributionStrategy $distributor) {
  378. if (isset($this->_hash)) {
  379. return $this->_hash;
  380. }
  381. if (isset($this->_arguments[0])) {
  382. // TODO: should we throw an exception if the command does
  383. // not support sharding?
  384. $key = $this->_arguments[0];
  385. $start = strpos($key, '{');
  386. if ($start !== false) {
  387. $end = strpos($key, '}', $start);
  388. if ($end !== false) {
  389. $key = substr($key, ++$start, $end - $start);
  390. }
  391. }
  392. $this->_hash = $distributor->generateKey($key);
  393. return $this->_hash;
  394. }
  395. return null;
  396. }
  397. public function closesConnection() {
  398. return false;
  399. }
  400. protected function filterArguments(Array $arguments) {
  401. return $arguments;
  402. }
  403. public function setArguments(/* arguments */) {
  404. $this->_arguments = $this->filterArguments(func_get_args());
  405. unset($this->_hash);
  406. }
  407. public function setArgumentsArray(Array $arguments) {
  408. $this->_arguments = $this->filterArguments($arguments);
  409. unset($this->_hash);
  410. }
  411. public function getArguments() {
  412. return $this->_arguments;
  413. }
  414. public function getArgument($index = 0) {
  415. if (isset($this->_arguments[$index]) === true) {
  416. return $this->_arguments[$index];
  417. }
  418. }
  419. public function parseResponse($data) {
  420. return $data;
  421. }
  422. public final function __invoke() {
  423. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  424. }
  425. private static function reduceArguments($str, $arg) {
  426. if (strlen($arg) > 32) {
  427. $arg = substr($arg, 0, 32) . '[...]';
  428. }
  429. $str .= " $arg";
  430. return $str;
  431. }
  432. public function __toString() {
  433. return array_reduce($this->getArguments(), 'self::reduceArguments', $this->getCommandId());
  434. }
  435. }
  436. abstract class InlineCommand extends Command {
  437. public function serializeRequest($command, $arguments) {
  438. if (isset($arguments[0]) && is_array($arguments[0])) {
  439. $arguments[0] = implode($arguments[0], ' ');
  440. }
  441. return $command . (count($arguments) > 0
  442. ? ' ' . implode($arguments, ' ') . "\r\n" : "\r\n"
  443. );
  444. }
  445. }
  446. abstract class BulkCommand extends Command {
  447. public function serializeRequest($command, $arguments) {
  448. $data = array_pop($arguments);
  449. if (is_array($data)) {
  450. $data = implode($data, ' ');
  451. }
  452. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  453. "\r\n" . $data . "\r\n";
  454. }
  455. }
  456. abstract class MultiBulkCommand extends Command {
  457. public function serializeRequest($command, $arguments) {
  458. $cmd_args = null;
  459. $argsc = count($arguments);
  460. if ($argsc === 1 && is_array($arguments[0])) {
  461. $cmd_args = $arguments[0];
  462. $argsc = count($cmd_args);
  463. }
  464. else {
  465. $cmd_args = $arguments;
  466. }
  467. $cmdlen = strlen($command);
  468. $reqlen = $argsc + 1;
  469. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$command}\r\n";
  470. for ($i = 0; $i < $reqlen - 1; $i++) {
  471. $argument = $cmd_args[$i];
  472. $arglen = strlen($argument);
  473. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  474. }
  475. return $buffer;
  476. }
  477. }
  478. /* ------------------------------------------------------------------------- */
  479. interface IResponseHandler {
  480. function handle(Connection $connection, $payload);
  481. }
  482. class ResponseStatusHandler implements IResponseHandler {
  483. public function handle(Connection $connection, $status) {
  484. if ($status === 'OK') {
  485. return true;
  486. }
  487. if ($status === 'QUEUED') {
  488. return new ResponseQueued();
  489. }
  490. return $status;
  491. }
  492. }
  493. class ResponseErrorHandler implements IResponseHandler {
  494. public function handle(Connection $connection, $errorMessage) {
  495. throw new ServerException(substr($errorMessage, 4));
  496. }
  497. }
  498. class ResponseErrorSilentHandler implements IResponseHandler {
  499. public function handle(Connection $connection, $errorMessage) {
  500. return new ResponseError(substr($errorMessage, 4));
  501. }
  502. }
  503. class ResponseBulkHandler implements IResponseHandler {
  504. public function handle(Connection $connection, $lengthString) {
  505. $length = (int) $lengthString;
  506. if ($length != $lengthString) {
  507. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  508. $connection, "Cannot parse '$length' as data length"
  509. ));
  510. }
  511. if ($length >= 0) {
  512. return substr($connection->readBytes($length + 2), 0, -2);
  513. }
  514. if ($length == -1) {
  515. return null;
  516. }
  517. }
  518. }
  519. class ResponseMultiBulkHandler implements IResponseHandler {
  520. public function handle(Connection $connection, $lengthString) {
  521. $listLength = (int) $lengthString;
  522. if ($listLength != $lengthString) {
  523. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  524. $connection, "Cannot parse '$lengthString' as data length"
  525. ));
  526. }
  527. if ($listLength === -1) {
  528. return null;
  529. }
  530. $list = array();
  531. if ($listLength > 0) {
  532. $handlers = array();
  533. $reader = $connection->getResponseReader();
  534. for ($i = 0; $i < $listLength; $i++) {
  535. $header = $connection->readLine();
  536. $prefix = $header[0];
  537. if (isset($handlers[$prefix])) {
  538. $handler = $handlers[$prefix];
  539. }
  540. else {
  541. $handler = $reader->getHandler($prefix);
  542. $handlers[$prefix] = $handler;
  543. }
  544. $list[$i] = $handler->handle($connection, substr($header, 1));
  545. }
  546. }
  547. return $list;
  548. }
  549. }
  550. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  551. public function handle(Connection $connection, $lengthString) {
  552. $listLength = (int) $lengthString;
  553. if ($listLength != $lengthString) {
  554. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  555. $connection, "Cannot parse '$lengthString' as data length"
  556. ));
  557. }
  558. return new Shared\MultiBulkResponseIterator($connection, $lengthString);
  559. }
  560. }
  561. class ResponseIntegerHandler implements IResponseHandler {
  562. public function handle(Connection $connection, $number) {
  563. if (is_numeric($number)) {
  564. return (int) $number;
  565. }
  566. if ($number !== 'nil') {
  567. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  568. $connection, "Cannot parse '$number' as numeric response"
  569. ));
  570. }
  571. return null;
  572. }
  573. }
  574. interface IResponseReader {
  575. public function read(Connection $connection);
  576. public function setOption($option, $value);
  577. public function getOption($option);
  578. }
  579. class FastResponseReader implements IResponseReader {
  580. private $_iterableMultibulk, $_throwErrors;
  581. public function __construct() {
  582. $this->_iterableMultibulk = false;
  583. $this->_throwErrors = true;
  584. }
  585. public function read(Connection $connection) {
  586. $chunk = $connection->readLine();
  587. $prefix = $chunk[0];
  588. $payload = substr($chunk, 1);
  589. switch ($prefix) {
  590. case '+': // inline
  591. switch ($payload) {
  592. case 'OK':
  593. return true;
  594. case 'QUEUED':
  595. return new ResponseQueued();
  596. default:
  597. return $payload;
  598. }
  599. case '$': // bulk
  600. $size = (int) $payload;
  601. if ($size === -1) {
  602. return null;
  603. }
  604. return substr($connection->readBytes($size + 2), 0, -2);
  605. case '*': // multi bulk
  606. $count = (int) $payload;
  607. if ($count === -1) {
  608. return null;
  609. }
  610. if ($this->_iterableMultibulk) {
  611. return new \Predis\Shared\MultiBulkResponseIterator($connection, $count);
  612. }
  613. $multibulk = array();
  614. for ($i = 0; $i < $count; $i++) {
  615. $multibulk[$i] = $this->read($connection);
  616. }
  617. return $multibulk;
  618. case ':': // integer
  619. return (int) $payload;
  620. case '-': // error
  621. $errorMessage = substr($payload, 4);
  622. if ($this->_throwErrors) {
  623. throw new ServerException($errorMessage);
  624. }
  625. return new ResponseError($errorMessage);
  626. default:
  627. throw new CommunicationException(
  628. $connection, "Unknown prefix: '$prefix'"
  629. );
  630. }
  631. }
  632. public function setOption($option, $value) {
  633. switch ($option) {
  634. case 'iterable_multibulk':
  635. $this->_iterableMultibulk = (bool) $value;
  636. break;
  637. case 'throw_on_error':
  638. $this->_throwErrors = (bool) $value;
  639. break;
  640. }
  641. }
  642. public function getOption($option) {
  643. switch ($option) {
  644. case 'iterable_multibulk':
  645. return $this->_iterableMultibulk;
  646. case 'throw_on_error':
  647. return $this->_throwErrors;
  648. }
  649. }
  650. }
  651. class ResponseReader implements IResponseReader {
  652. private $_prefixHandlers;
  653. public function __construct() {
  654. $this->initializePrefixHandlers();
  655. }
  656. private function initializePrefixHandlers() {
  657. $this->_prefixHandlers = array(
  658. Protocol::PREFIX_STATUS => new ResponseStatusHandler(),
  659. Protocol::PREFIX_ERROR => new ResponseErrorHandler(),
  660. Protocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
  661. Protocol::PREFIX_BULK => new ResponseBulkHandler(),
  662. Protocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  663. );
  664. }
  665. public function setHandler($prefix, IResponseHandler $handler) {
  666. $this->_prefixHandlers[$prefix] = $handler;
  667. }
  668. public function getHandler($prefix) {
  669. if (isset($this->_prefixHandlers[$prefix])) {
  670. return $this->_prefixHandlers[$prefix];
  671. }
  672. }
  673. public function read(Connection $connection) {
  674. $header = $connection->readLine();
  675. if ($header === '') {
  676. $this->throwMalformedResponse($connection, 'Unexpected empty header');
  677. }
  678. $prefix = $header[0];
  679. if (!isset($this->_prefixHandlers[$prefix])) {
  680. $this->throwMalformedResponse($connection, "Unknown prefix '$prefix'");
  681. }
  682. $handler = $this->_prefixHandlers[$prefix];
  683. return $handler->handle($connection, substr($header, 1));
  684. }
  685. private function throwMalformedResponse(Connection $connection, $message) {
  686. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  687. $connection, $message
  688. ));
  689. }
  690. public function setOption($option, $value) {
  691. switch ($option) {
  692. case 'iterable_multibulk':
  693. $handler = $value ? 'Predis\ResponseMultiBulkStreamHandler' : 'Predis\ResponseMultiBulkHandler';
  694. $this->_prefixHandlers[Protocol::PREFIX_MULTI_BULK] = new $handler();
  695. break;
  696. case 'throw_on_error':
  697. $handler = $value ? 'Predis\ResponseErrorHandler' : 'Predis\ResponseErrorSilentHandler';
  698. $this->_prefixHandlers[Protocol::PREFIX_ERROR] = new $handler();
  699. break;
  700. }
  701. }
  702. public function getOption($option) {
  703. switch ($option) {
  704. case 'iterable_multibulk':
  705. return $this->_prefixHandlers[Protocol::PREFIX_MULTI_BULK] instanceof ResponseMultiBulkStreamHandler;
  706. case 'throw_on_error':
  707. return $this->_prefixHandlers[Protocol::PREFIX_ERROR] instanceof ResponseErrorHandler;
  708. }
  709. }
  710. }
  711. class ResponseError {
  712. public $skipParse = true;
  713. private $_message;
  714. public function __construct($message) {
  715. $this->_message = $message;
  716. }
  717. public function __get($property) {
  718. if ($property === 'error') {
  719. return true;
  720. }
  721. if ($property === 'message') {
  722. return $this->_message;
  723. }
  724. }
  725. public function __isset($property) {
  726. return $property === 'error';
  727. }
  728. public function __toString() {
  729. return $this->_message;
  730. }
  731. }
  732. class ResponseQueued {
  733. public $skipParse = true;
  734. public function __toString() {
  735. return Protocol::QUEUED;
  736. }
  737. public function __get($property) {
  738. if ($property === 'queued') {
  739. return true;
  740. }
  741. }
  742. public function __isset($property) {
  743. return $property === 'queued';
  744. }
  745. }
  746. /* ------------------------------------------------------------------------- */
  747. class CommandPipeline {
  748. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running, $_executor;
  749. public function __construct(Client $redisClient, Pipeline\IPipelineExecutor $executor = null) {
  750. $this->_redisClient = $redisClient;
  751. $this->_executor = $executor ?: new Pipeline\StandardExecutor();
  752. $this->_pipelineBuffer = array();
  753. $this->_returnValues = array();
  754. }
  755. public function __call($method, $arguments) {
  756. $command = $this->_redisClient->createCommand($method, $arguments);
  757. $this->recordCommand($command);
  758. return $this;
  759. }
  760. private function recordCommand(Command $command) {
  761. $this->_pipelineBuffer[] = $command;
  762. }
  763. private function getRecordedCommands() {
  764. return $this->_pipelineBuffer;
  765. }
  766. public function flushPipeline() {
  767. if (count($this->_pipelineBuffer) > 0) {
  768. $connection = $this->_redisClient->getConnection();
  769. $this->_returnValues = array_merge(
  770. $this->_returnValues,
  771. $this->_executor->execute($connection, $this->_pipelineBuffer)
  772. );
  773. $this->_pipelineBuffer = array();
  774. }
  775. return $this;
  776. }
  777. private function setRunning($bool) {
  778. if ($bool == true && $this->_running == true) {
  779. throw new ClientException("This pipeline is already opened");
  780. }
  781. $this->_running = $bool;
  782. }
  783. public function execute($block = null) {
  784. if ($block && !is_callable($block)) {
  785. throw new \InvalidArgumentException('Argument passed must be a callable object');
  786. }
  787. // TODO: do not reuse previously executed pipelines
  788. $this->setRunning(true);
  789. $pipelineBlockException = null;
  790. try {
  791. if ($block !== null) {
  792. $block($this);
  793. }
  794. $this->flushPipeline();
  795. }
  796. catch (\Exception $exception) {
  797. $pipelineBlockException = $exception;
  798. }
  799. $this->setRunning(false);
  800. if ($pipelineBlockException !== null) {
  801. throw $pipelineBlockException;
  802. }
  803. return $this->_returnValues;
  804. }
  805. }
  806. class MultiExecBlock {
  807. private $_initialized, $_discarded, $_insideBlock, $_checkAndSet, $_watchedKeys;
  808. private $_redisClient, $_options, $_commands;
  809. private $_supportsWatch;
  810. public function __construct(Client $redisClient, Array $options = null) {
  811. $this->checkCapabilities($redisClient);
  812. $this->_options = $options ?: array();
  813. $this->_redisClient = $redisClient;
  814. $this->reset();
  815. }
  816. private function checkCapabilities(Client $redisClient) {
  817. if (Shared\Utils::isCluster($redisClient->getConnection())) {
  818. throw new \Predis\ClientException(
  819. 'Cannot initialize a MULTI/EXEC context over a cluster of connections'
  820. );
  821. }
  822. $profile = $redisClient->getProfile();
  823. if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
  824. throw new \Predis\ClientException(
  825. 'The current profile does not support MULTI, EXEC and DISCARD commands'
  826. );
  827. }
  828. $this->_supportsWatch = $profile->supportsCommands(array('watch', 'unwatch'));
  829. }
  830. private function isWatchSupported() {
  831. if ($this->_supportsWatch === false) {
  832. throw new \Predis\ClientException(
  833. 'The current profile does not support WATCH and UNWATCH commands'
  834. );
  835. }
  836. }
  837. private function reset() {
  838. $this->_initialized = false;
  839. $this->_discarded = false;
  840. $this->_checkAndSet = false;
  841. $this->_insideBlock = false;
  842. $this->_watchedKeys = false;
  843. $this->_commands = array();
  844. }
  845. private function initialize() {
  846. if ($this->_initialized === true) {
  847. return;
  848. }
  849. $options = &$this->_options;
  850. $this->_checkAndSet = isset($options['cas']) && $options['cas'];
  851. if (isset($options['watch'])) {
  852. $this->watch($options['watch']);
  853. }
  854. if (!$this->_checkAndSet || ($this->_discarded && $this->_checkAndSet)) {
  855. $this->_redisClient->multi();
  856. if ($this->_discarded) {
  857. $this->_checkAndSet = false;
  858. }
  859. }
  860. $this->_initialized = true;
  861. $this->_discarded = false;
  862. }
  863. public function __call($method, $arguments) {
  864. $this->initialize();
  865. $client = $this->_redisClient;
  866. if ($this->_checkAndSet) {
  867. return call_user_func_array(array($client, $method), $arguments);
  868. }
  869. $command = $client->createCommand($method, $arguments);
  870. $response = $client->executeCommand($command);
  871. if (!$response instanceof \Predis\ResponseQueued) {
  872. $this->malformedServerResponse(
  873. 'The server did not respond with a QUEUED status reply'
  874. );
  875. }
  876. $this->_commands[] = $command;
  877. return $this;
  878. }
  879. public function watch($keys) {
  880. $this->isWatchSupported();
  881. if ($this->_initialized && !$this->_checkAndSet) {
  882. throw new ClientException('WATCH inside MULTI is not allowed');
  883. }
  884. $this->_watchedKeys = true;
  885. return $this->_redisClient->watch($keys);
  886. }
  887. public function multi() {
  888. if ($this->_initialized && $this->_checkAndSet) {
  889. $this->_checkAndSet = false;
  890. $this->_redisClient->multi();
  891. return $this;
  892. }
  893. $this->initialize();
  894. return $this;
  895. }
  896. public function unwatch() {
  897. $this->isWatchSupported();
  898. $this->_watchedKeys = false;
  899. $this->_redisClient->unwatch();
  900. return $this;
  901. }
  902. public function discard() {
  903. if ($this->_initialized === true) {
  904. $command = $this->_checkAndSet ? 'unwatch' : 'discard';
  905. $this->_redisClient->$command();
  906. $this->reset();
  907. $this->_discarded = true;
  908. }
  909. return $this;
  910. }
  911. public function exec() {
  912. return $this->execute();
  913. }
  914. private function checkBeforeExecution($block) {
  915. if ($this->_insideBlock === true) {
  916. throw new \Predis\ClientException(
  917. "Cannot invoke 'execute' or 'exec' inside an active client transaction block"
  918. );
  919. }
  920. if ($block) {
  921. if (!is_callable($block)) {
  922. throw new \InvalidArgumentException(
  923. 'Argument passed must be a callable object'
  924. );
  925. }
  926. if (count($this->_commands) > 0) {
  927. $this->discard();
  928. throw new ClientException(
  929. 'Cannot execute a transaction block after using fluent interface'
  930. );
  931. }
  932. }
  933. if (isset($this->_options['retry']) && !isset($block)) {
  934. $this->discard();
  935. throw new \InvalidArgumentException(
  936. 'Automatic retries can be used only when a transaction block is provided'
  937. );
  938. }
  939. }
  940. public function execute($block = null) {
  941. $this->checkBeforeExecution($block);
  942. $reply = null;
  943. $returnValues = array();
  944. $attemptsLeft = isset($this->_options['retry']) ? (int)$this->_options['retry'] : 0;
  945. do {
  946. $blockException = null;
  947. if ($block !== null) {
  948. $this->_insideBlock = true;
  949. try {
  950. $block($this);
  951. }
  952. catch (CommunicationException $exception) {
  953. $blockException = $exception;
  954. }
  955. catch (ServerException $exception) {
  956. $blockException = $exception;
  957. }
  958. catch (\Exception $exception) {
  959. $blockException = $exception;
  960. $this->discard();
  961. }
  962. $this->_insideBlock = false;
  963. if ($blockException !== null) {
  964. throw $blockException;
  965. }
  966. }
  967. if (count($this->_commands) === 0) {
  968. if ($this->_watchedKeys) {
  969. $this->discard();
  970. return;
  971. }
  972. return;
  973. }
  974. $reply = $this->_redisClient->exec();
  975. if ($reply === null) {
  976. if ($attemptsLeft === 0) {
  977. throw new AbortedMultiExec(
  978. 'The current transaction has been aborted by the server'
  979. );
  980. }
  981. $this->reset();
  982. if (isset($this->_options['on_retry']) && is_callable($this->_options['on_retry'])) {
  983. call_user_func($this->_options['on_retry'], $this, $attemptsLeft);
  984. }
  985. continue;
  986. }
  987. break;
  988. } while ($attemptsLeft-- > 0);
  989. $execReply = $reply instanceof \Iterator ? iterator_to_array($reply) : $reply;
  990. $sizeofReplies = count($execReply);
  991. $commands = &$this->_commands;
  992. if ($sizeofReplies !== count($commands)) {
  993. $this->malformedServerResponse(
  994. 'Unexpected number of responses for a MultiExecBlock'
  995. );
  996. }
  997. for ($i = 0; $i < $sizeofReplies; $i++) {
  998. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  999. ? iterator_to_array($execReply[$i])
  1000. : $execReply[$i]
  1001. );
  1002. unset($commands[$i]);
  1003. }
  1004. return $returnValues;
  1005. }
  1006. private function malformedServerResponse($message) {
  1007. // Since a MULTI/EXEC block cannot be initialized over a clustered
  1008. // connection, we can safely assume that Predis\Client::getConnection()
  1009. // will always return an instance of Predis\Connection.
  1010. Shared\Utils::onCommunicationException(new MalformedServerResponse(
  1011. $this->_redisClient->getConnection(), $message
  1012. ));
  1013. }
  1014. }
  1015. class PubSubContext implements \Iterator {
  1016. const SUBSCRIBE = 'subscribe';
  1017. const UNSUBSCRIBE = 'unsubscribe';
  1018. const PSUBSCRIBE = 'psubscribe';
  1019. const PUNSUBSCRIBE = 'punsubscribe';
  1020. const MESSAGE = 'message';
  1021. const PMESSAGE = 'pmessage';
  1022. const STATUS_VALID = 0x0001;
  1023. const STATUS_SUBSCRIBED = 0x0010;
  1024. const STATUS_PSUBSCRIBED = 0x0100;
  1025. private $_redisClient, $_position, $_options;
  1026. public function __construct(Client $redisClient, Array $options = null) {
  1027. $this->checkCapabilities($redisClient);
  1028. $this->_options = $options ?: array();
  1029. $this->_redisClient = $redisClient;
  1030. $this->_statusFlags = self::STATUS_VALID;
  1031. $this->genericSubscribeInit('subscribe');
  1032. $this->genericSubscribeInit('psubscribe');
  1033. }
  1034. public function __destruct() {
  1035. $this->closeContext();
  1036. }
  1037. private function checkCapabilities(Client $redisClient) {
  1038. if (Shared\Utils::isCluster($redisClient->getConnection())) {
  1039. throw new \Predis\ClientException(
  1040. 'Cannot initialize a PUB/SUB context over a cluster of connections'
  1041. );
  1042. }
  1043. $profile = $redisClient->getProfile();
  1044. $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
  1045. if ($profile->supportsCommands($commands) === false) {
  1046. throw new \Predis\ClientException(
  1047. 'The current profile does not support PUB/SUB related commands'
  1048. );
  1049. }
  1050. }
  1051. private function genericSubscribeInit($subscribeAction) {
  1052. if (isset($this->_options[$subscribeAction])) {
  1053. $this->$subscribeAction($this->_options[$subscribeAction]);
  1054. }
  1055. }
  1056. private function isFlagSet($value) {
  1057. return ($this->_statusFlags & $value) === $value;
  1058. }
  1059. public function subscribe(/* arguments */) {
  1060. $this->writeCommand(self::SUBSCRIBE, func_get_args());
  1061. $this->_statusFlags |= self::STATUS_SUBSCRIBED;
  1062. }
  1063. public function unsubscribe(/* arguments */) {
  1064. $this->writeCommand(self::UNSUBSCRIBE, func_get_args());
  1065. }
  1066. public function psubscribe(/* arguments */) {
  1067. $this->writeCommand(self::PSUBSCRIBE, func_get_args());
  1068. $this->_statusFlags |= self::STATUS_PSUBSCRIBED;
  1069. }
  1070. public function punsubscribe(/* arguments */) {
  1071. $this->writeCommand(self::PUNSUBSCRIBE, func_get_args());
  1072. }
  1073. public function closeContext() {
  1074. if ($this->valid()) {
  1075. if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
  1076. $this->unsubscribe();
  1077. }
  1078. if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
  1079. $this->punsubscribe();
  1080. }
  1081. }
  1082. }
  1083. private function writeCommand($method, $arguments) {
  1084. if (count($arguments) === 1 && is_array($arguments[0])) {
  1085. $arguments = $arguments[0];
  1086. }
  1087. $command = $this->_redisClient->createCommand($method, $arguments);
  1088. $this->_redisClient->getConnection()->writeCommand($command);
  1089. }
  1090. public function rewind() {
  1091. // NOOP
  1092. }
  1093. public function current() {
  1094. return $this->getValue();
  1095. }
  1096. public function key() {
  1097. return $this->_position;
  1098. }
  1099. public function next() {
  1100. if ($this->isFlagSet(self::STATUS_VALID)) {
  1101. $this->_position++;
  1102. }
  1103. return $this->_position;
  1104. }
  1105. public function valid() {
  1106. $subscriptions = self::STATUS_SUBSCRIBED + self::STATUS_PSUBSCRIBED;
  1107. return $this->isFlagSet(self::STATUS_VALID)
  1108. && ($this->_statusFlags & $subscriptions) > 0;
  1109. }
  1110. private function invalidate() {
  1111. $this->_statusFlags = 0x0000;
  1112. }
  1113. private function getValue() {
  1114. $reader = $this->_redisClient->getResponseReader();
  1115. $connection = $this->_redisClient->getConnection();
  1116. $response = $reader->read($connection);
  1117. switch ($response[0]) {
  1118. case self::SUBSCRIBE:
  1119. case self::UNSUBSCRIBE:
  1120. case self::PSUBSCRIBE:
  1121. case self::PUNSUBSCRIBE:
  1122. if ($response[2] === 0) {
  1123. $this->invalidate();
  1124. }
  1125. case self::MESSAGE:
  1126. return (object) array(
  1127. 'kind' => $response[0],
  1128. 'channel' => $response[1],
  1129. 'payload' => $response[2],
  1130. );
  1131. case self::PMESSAGE:
  1132. return (object) array(
  1133. 'kind' => $response[0],
  1134. 'pattern' => $response[1],
  1135. 'channel' => $response[2],
  1136. 'payload' => $response[3],
  1137. );
  1138. default:
  1139. throw new \Predis\ClientException(
  1140. "Received an unknown message type {$response[0]} inside of a pubsub context"
  1141. );
  1142. }
  1143. }
  1144. }
  1145. /* ------------------------------------------------------------------------- */
  1146. class ConnectionParameters {
  1147. const DEFAULT_SCHEME = 'redis';
  1148. const DEFAULT_HOST = '127.0.0.1';
  1149. const DEFAULT_PORT = 6379;
  1150. const DEFAULT_TIMEOUT = 5;
  1151. private static $_defaultParameters = array(
  1152. 'scheme' => self::DEFAULT_SCHEME,
  1153. 'host' => self::DEFAULT_HOST,
  1154. 'port' => self::DEFAULT_PORT,
  1155. 'database' => null,
  1156. 'password' => null,
  1157. 'connection_async' => false,
  1158. 'connection_persistent' => false,
  1159. 'connection_timeout' => self::DEFAULT_TIMEOUT,
  1160. 'read_write_timeout' => null,
  1161. 'alias' => null,
  1162. 'weight' => null,
  1163. 'path' => null,
  1164. );
  1165. private $_parameters;
  1166. public function __construct($parameters = null) {
  1167. $parameters = $parameters ?: array();
  1168. $extractor = is_array($parameters) ? 'filter' : 'parseURI';
  1169. $this->_parameters = $this->$extractor($parameters);
  1170. }
  1171. private function parseURI($uri) {
  1172. if (stripos($uri, 'unix') === 0) {
  1173. // Hack to support URIs for UNIX sockets with minimal effort.
  1174. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  1175. }
  1176. if (($parsed = @parse_url($uri)) === false || !isset($parsed['host'])) {
  1177. throw new ClientException("Invalid URI: $uri");
  1178. }
  1179. if (isset($parsed['query'])) {
  1180. foreach (explode('&', $parsed['query']) as $kv) {
  1181. @list($k, $v) = explode('=', $kv);
  1182. $parsed[$k] = $v;
  1183. }
  1184. unset($parsed['query']);
  1185. }
  1186. return $this->filter($parsed);
  1187. }
  1188. private function filter($parameters) {
  1189. return array_merge(self::$_defaultParameters, $parameters);
  1190. }
  1191. public function __get($parameter) {
  1192. return $this->_parameters[$parameter];
  1193. }
  1194. public function __isset($parameter) {
  1195. return isset($this->_parameters[$parameter]);
  1196. }
  1197. }
  1198. interface IConnection {
  1199. public function connect();
  1200. public function disconnect();
  1201. public function isConnected();
  1202. public function writeCommand(Command $command);
  1203. public function readResponse(Command $command);
  1204. public function executeCommand(Command $command);
  1205. }
  1206. class Connection implements IConnection {
  1207. private static $_allowedSchemes = array('redis', 'tcp', 'unix');
  1208. private $_params, $_socket, $_initCmds, $_reader;
  1209. public function __construct(ConnectionParameters $parameters, IResponseReader $reader = null) {
  1210. if (!in_array($parameters->scheme, self::$_allowedSchemes)) {
  1211. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1212. }
  1213. $this->_params = $parameters;
  1214. $this->_initCmds = array();
  1215. $this->_reader = $reader ?: new FastResponseReader();
  1216. }
  1217. public function __destruct() {
  1218. if (!$this->_params->connection_persistent) {
  1219. $this->disconnect();
  1220. }
  1221. }
  1222. public function isConnected() {
  1223. return isset($this->_socket);
  1224. }
  1225. public function connect() {
  1226. if ($this->isConnected()) {
  1227. throw new ClientException('Connection already estabilished');
  1228. }
  1229. $initializer = "{$this->_params->scheme}StreamInitializer";
  1230. $this->_socket = $this->$initializer($this->_params);
  1231. if (count($this->_initCmds) > 0){
  1232. $this->sendInitializationCommands();
  1233. }
  1234. }
  1235. private function tcpStreamInitializer(ConnectionParameters $parameters) {
  1236. return $this->redisStreamInitializer($parameters);
  1237. }
  1238. private function redisStreamInitializer(ConnectionParameters $parameters) {
  1239. $uri = sprintf('tcp://%s:%d/', $parameters->host, $parameters->port);
  1240. $connectFlags = STREAM_CLIENT_CONNECT;
  1241. if ($parameters->connection_async) {
  1242. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1243. }
  1244. if ($parameters->connection_persistent) {
  1245. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1246. }
  1247. $socket = @stream_socket_client(
  1248. $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
  1249. );
  1250. if (!$socket) {
  1251. $this->onCommunicationException(trim($errstr), $errno);
  1252. }
  1253. if (isset($parameters->read_write_timeout)) {
  1254. $rwtimeout = $parameters->read_write_timeout;
  1255. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  1256. $timeoutSeconds = floor($parameters->read_write_timeout);
  1257. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  1258. stream_set_timeout($socket, $rwtimeout, $timeoutUSeconds);
  1259. }
  1260. return $socket;
  1261. }
  1262. private function unixStreamInitializer(ConnectionParameters $parameters) {
  1263. $uri = sprintf('unix:///%s', $parameters->path);
  1264. $connectFlags = STREAM_CLIENT_CONNECT;
  1265. if ($parameters->connection_persistent) {
  1266. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1267. }
  1268. $socket = @stream_socket_client(
  1269. $uri, $errno, $errstr, $parameters->connection_timeout, $connectFlags
  1270. );
  1271. if (!$socket) {
  1272. $this->onCommunicationException(trim($errstr), $errno);
  1273. }
  1274. return $socket;
  1275. }
  1276. public function disconnect() {
  1277. if ($this->isConnected()) {
  1278. fclose($this->_socket);
  1279. unset($this->_socket);
  1280. }
  1281. }
  1282. public function pushInitCommand(Command $command){
  1283. $this->_initCmds[] = $command;
  1284. }
  1285. private function sendInitializationCommands() {
  1286. foreach ($this->_initCmds as $command) {
  1287. $this->writeCommand($command);
  1288. }
  1289. foreach ($this->_initCmds as $command) {
  1290. $this->readResponse($command);
  1291. }
  1292. }
  1293. private function onCommunicationException($message, $code = null) {
  1294. Shared\Utils::onCommunicationException(
  1295. new CommunicationException($this, $message, $code)
  1296. );
  1297. }
  1298. public function writeCommand(Command $command) {
  1299. $this->writeBytes($command());
  1300. }
  1301. public function readResponse(Command $command) {
  1302. $response = $this->_reader->read($this);
  1303. return isset($response->skipParse) ? $response : $command->parseResponse($response);
  1304. }
  1305. public function executeCommand(Command $command) {
  1306. $this->writeCommand($command);
  1307. if ($command->closesConnection()) {
  1308. return $this->disconnect();
  1309. }
  1310. return $this->readResponse($command);
  1311. }
  1312. public function rawCommand($rawCommandData, $closesConnection = false) {
  1313. $this->writeBytes($rawCommandData);
  1314. if ($closesConnection) {
  1315. $this->disconnect();
  1316. return;
  1317. }
  1318. return $this->_reader->read($this);
  1319. }
  1320. public function writeBytes($value) {
  1321. $socket = $this->getSocket();
  1322. while (($length = strlen($value)) > 0) {
  1323. $written = fwrite($socket, $value);
  1324. if ($length === $written) {
  1325. return true;
  1326. }
  1327. if ($written === false || $written === 0) {
  1328. $this->onCommunicationException('Error while writing bytes to the server');
  1329. }
  1330. $value = substr($value, $written);
  1331. }
  1332. return true;
  1333. }
  1334. public function readBytes($length) {
  1335. if ($length <= 0) {
  1336. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1337. }
  1338. $socket = $this->getSocket();
  1339. $value = '';
  1340. do {
  1341. $chunk = fread($socket, $length);
  1342. if ($chunk === false || $chunk === '') {
  1343. $this->onCommunicationException('Error while reading bytes from the server');
  1344. }
  1345. $value .= $chunk;
  1346. }
  1347. while (($length -= strlen($chunk)) > 0);
  1348. return $value;
  1349. }
  1350. public function readLine() {
  1351. $socket = $this->getSocket();
  1352. $value = '';
  1353. do {
  1354. $chunk = fgets($socket);
  1355. if ($chunk === false || $chunk === '') {
  1356. $this->onCommunicationException('Error while reading line from the server');
  1357. }
  1358. $value .= $chunk;
  1359. }
  1360. while (substr($value, -2) !== "\r\n");
  1361. return substr($value, 0, -2);
  1362. }
  1363. public function getSocket() {
  1364. if (isset($this->_socket)) {
  1365. return $this->_socket;
  1366. }
  1367. $this->connect();
  1368. return $this->_socket;
  1369. }
  1370. public function getResponseReader() {
  1371. return $this->_reader;
  1372. }
  1373. public function getParameters() {
  1374. return $this->_params;
  1375. }
  1376. public function __toString() {
  1377. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  1378. }
  1379. }
  1380. class ConnectionCluster implements IConnection, \IteratorAggregate {
  1381. private $_pool, $_distributor;
  1382. public function __construct(Distribution\IDistributionStrategy $distributor = null) {
  1383. $this->_pool = array();
  1384. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1385. }
  1386. public function isConnected() {
  1387. foreach ($this->_pool as $connection) {
  1388. if ($connection->isConnected()) {
  1389. return true;
  1390. }
  1391. }
  1392. return false;
  1393. }
  1394. public function connect() {
  1395. foreach ($this->_pool as $connection) {
  1396. $connection->connect();
  1397. }
  1398. }
  1399. public function disconnect() {
  1400. foreach ($this->_pool as $connection) {
  1401. $connection->disconnect();
  1402. }
  1403. }
  1404. public function add(Connection $connection) {
  1405. $parameters = $connection->getParameters();
  1406. if (isset($parameters->alias)) {
  1407. $this->_pool[$parameters->alias] = $connection;
  1408. }
  1409. else {
  1410. $this->_pool[] = $connection;
  1411. }
  1412. $this->_distributor->add($connection, $parameters->weight);
  1413. }
  1414. public function getConnection(Command $command) {
  1415. if ($command->canBeHashed() === false) {
  1416. throw new ClientException(
  1417. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1418. );
  1419. }
  1420. return $this->_distributor->get($command->getHash($this->_distributor));
  1421. }
  1422. public function getConnectionById($id = null) {
  1423. $alias = $id ?: 0;
  1424. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1425. }
  1426. public function getIterator() {
  1427. return new \ArrayIterator($this->_pool);
  1428. }
  1429. public function writeCommand(Command $command) {
  1430. $this->getConnection($command)->writeCommand($command);
  1431. }
  1432. public function readResponse(Command $command) {
  1433. return $this->getConnection($command)->readResponse($command);
  1434. }
  1435. public function executeCommand(Command $command) {
  1436. $connection = $this->getConnection($command);
  1437. $connection->writeCommand($command);
  1438. return $connection->readResponse($command);
  1439. }
  1440. }
  1441. /* ------------------------------------------------------------------------- */
  1442. abstract class RedisServerProfile {
  1443. private static $_serverProfiles;
  1444. private $_registeredCommands;
  1445. public function __construct() {
  1446. $this->_registeredCommands = $this->getSupportedCommands();
  1447. }
  1448. public abstract function getVersion();
  1449. protected abstract function getSupportedCommands();
  1450. public static function getDefault() {
  1451. return self::get('default');
  1452. }
  1453. public static function getDevelopment() {
  1454. return self::get('dev');
  1455. }
  1456. private static function predisServerProfiles() {
  1457. return array(
  1458. '1.2' => '\Predis\RedisServer_v1_2',
  1459. '2.0' => '\Predis\RedisServer_v2_0',
  1460. '2.2' => '\Predis\RedisServer_v2_2',
  1461. 'default' => '\Predis\RedisServer_v2_2',
  1462. 'dev' => '\Predis\RedisServer_vNext',
  1463. );
  1464. }
  1465. public static function registerProfile($profileClass, $aliases) {
  1466. if (!isset(self::$_serverProfiles)) {
  1467. self::$_serverProfiles = self::predisServerProfiles();
  1468. }
  1469. $profileReflection = new \ReflectionClass($profileClass);
  1470. if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
  1471. throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1472. }
  1473. if (is_array($aliases)) {
  1474. foreach ($aliases as $alias) {
  1475. self::$_serverProfiles[$alias] = $profileClass;
  1476. }
  1477. }
  1478. else {
  1479. self::$_serverProfiles[$aliases] = $profileClass;
  1480. }
  1481. }
  1482. public static function get($version) {
  1483. if (!isset(self::$_serverProfiles)) {
  1484. self::$_serverProfiles = self::predisServerProfiles();
  1485. }
  1486. if (!isset(self::$_serverProfiles[$version])) {
  1487. throw new ClientException("Unknown server profile: $version");
  1488. }
  1489. $profile = self::$_serverProfiles[$version];
  1490. return new $profile();
  1491. }
  1492. public function supportsCommands(Array $commands) {
  1493. foreach ($commands as $command) {
  1494. if ($this->supportsCommand($command) === false) {
  1495. return false;
  1496. }
  1497. }
  1498. return true;
  1499. }
  1500. public function supportsCommand($command) {
  1501. return isset($this->_registeredCommands[$command]);
  1502. }
  1503. public function createCommand($method, $arguments = array()) {
  1504. if (!isset($this->_registeredCommands[$method])) {
  1505. throw new ClientException("'$method' is not a registered Redis command");
  1506. }
  1507. $commandClass = $this->_registeredCommands[$method];
  1508. $command = new $commandClass();
  1509. $command->setArgumentsArray($arguments);
  1510. return $command;
  1511. }
  1512. public function registerCommands(Array $commands) {
  1513. foreach ($commands as $command => $aliases) {
  1514. $this->registerCommand($command, $aliases);
  1515. }
  1516. }
  1517. public function registerCommand($command, $aliases) {
  1518. $commandReflection = new \ReflectionClass($command);
  1519. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  1520. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1521. }
  1522. if (is_array($aliases)) {
  1523. foreach ($aliases as $alias) {
  1524. $this->_registeredCommands[$alias] = $command;
  1525. }
  1526. }
  1527. else {
  1528. $this->_registeredCommands[$aliases] = $command;
  1529. }
  1530. }
  1531. public function __toString() {
  1532. return $this->getVersion();
  1533. }
  1534. }
  1535. class RedisServer_v1_2 extends RedisServerProfile {
  1536. public function getVersion() { return '1.2'; }
  1537. public function getSupportedCommands() {
  1538. return array(
  1539. /* ---------------- Redis 1.2 ---------------- */
  1540. /* miscellaneous commands */
  1541. 'ping' => '\Predis\Commands\Ping',
  1542. 'echo' => '\Predis\Commands\DoEcho',
  1543. 'auth' => '\Predis\Commands\Auth',
  1544. /* connection handling */
  1545. 'quit' => '\Predis\Commands\Quit',
  1546. /* commands operating on string values */
  1547. 'set' => '\Predis\Commands\Set',
  1548. 'setnx' => '\Predis\Commands\SetPreserve',
  1549. 'mset' => '\Predis\Commands\SetMultiple',
  1550. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1551. 'get' => '\Predis\Commands\Get',
  1552. 'mget' => '\Predis\Commands\GetMultiple',
  1553. 'getset' => '\Predis\Commands\GetSet',
  1554. 'incr' => '\Predis\Commands\Increment',
  1555. 'incrby' => '\Predis\Commands\IncrementBy',
  1556. 'decr' => '\Predis\Commands\Decrement',
  1557. 'decrby' => '\Predis\Commands\DecrementBy',
  1558. 'exists' => '\Predis\Commands\Exists',
  1559. 'del' => '\Predis\Commands\Delete',
  1560. 'type' => '\Predis\Commands\Type',
  1561. /* commands operating on the key space */
  1562. 'keys' => '\Predis\Commands\Keys_v1_2',
  1563. 'randomkey' => '\Predis\Commands\RandomKey',
  1564. 'rename' => '\Predis\Commands\Rename',
  1565. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1566. 'expire' => '\Predis\Commands\Expire',
  1567. 'expireat' => '\Predis\Commands\ExpireAt',
  1568. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1569. 'ttl' => '\Predis\Commands\TimeToLive',
  1570. /* commands operating on lists */
  1571. 'rpush' => '\Predis\Commands\ListPushTail',
  1572. 'lpush' => '\Predis\Commands\ListPushHead',
  1573. 'llen' => '\Predis\Commands\ListLength',
  1574. 'lrange' => '\Predis\Commands\ListRange',
  1575. 'ltrim' => '\Predis\Commands\ListTrim',
  1576. 'lindex' => '\Predis\Commands\ListIndex',
  1577. 'lset' => '\Predis\Commands\ListSet',
  1578. 'lrem' => '\Predis\Commands\ListRemove',
  1579. 'lpop' => '\Predis\Commands\ListPopFirst',
  1580. 'rpop' => '\Predis\Commands\ListPopLast',
  1581. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1582. /* commands operating on sets */
  1583. 'sadd' => '\Predis\Commands\SetAdd',
  1584. 'srem' => '\Predis\Commands\SetRemove',
  1585. 'spop' => '\Predis\Commands\SetPop',
  1586. 'smove' => '\Predis\Commands\SetMove',
  1587. 'scard' => '\Predis\Commands\SetCardinality',
  1588. 'sismember' => '\Predis\Commands\SetIsMember',
  1589. 'sinter' => '\Predis\Commands\SetIntersection',
  1590. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1591. 'sunion' => '\Predis\Commands\SetUnion',
  1592. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1593. 'sdiff' => '\Predis\Commands\SetDifference',
  1594. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1595. 'smembers' => '\Predis\Commands\SetMembers',
  1596. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1597. /* commands operating on sorted sets */
  1598. 'zadd' => '\Predis\Commands\ZSetAdd',
  1599. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1600. 'zrem' => '\Predis\Commands\ZSetRemove',
  1601. 'zrange' => '\Predis\Commands\ZSetRange',
  1602. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1603. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1604. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1605. 'zscore' => '\Predis\Commands\ZSetScore',
  1606. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1607. /* multiple databases handling commands */
  1608. 'select' => '\Predis\Commands\SelectDatabase',
  1609. 'move' => '\Predis\Commands\MoveKey',
  1610. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1611. 'flushall' => '\Predis\Commands\FlushAll',
  1612. /* sorting */
  1613. 'sort' => '\Predis\Commands\Sort',
  1614. /* remote server control commands */
  1615. 'info' => '\Predis\Commands\Info',
  1616. 'slaveof' => '\Predis\Commands\SlaveOf',
  1617. /* persistence control commands */
  1618. 'save' => '\Predis\Commands\Save',
  1619. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1620. 'lastsave' => '\Predis\Commands\LastSave',
  1621. 'shutdown' => '\Predis\Commands\Shutdown',
  1622. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1623. );
  1624. }
  1625. }
  1626. class RedisServer_v2_0 extends RedisServerProfile {
  1627. public function getVersion() { return '2.0'; }
  1628. public function getSupportedCommands() {
  1629. return array(
  1630. /* ---------------- Redis 1.2 ---------------- */
  1631. /* miscellaneous commands */
  1632. 'ping' => '\Predis\Commands\Ping',
  1633. 'echo' => '\Predis\Commands\DoEcho',
  1634. 'auth' => '\Predis\Commands\Auth',
  1635. /* connection handling */
  1636. 'quit' => '\Predis\Commands\Quit',
  1637. /* commands operating on string values */
  1638. 'set' => '\Predis\Commands\Set',
  1639. 'setnx' => '\Predis\Commands\SetPreserve',
  1640. 'mset' => '\Predis\Commands\SetMultiple',
  1641. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1642. 'get' => '\Predis\Commands\Get',
  1643. 'mget' => '\Predis\Commands\GetMultiple',
  1644. 'getset' => '\Predis\Commands\GetSet',
  1645. 'incr' => '\Predis\Commands\Increment',
  1646. 'incrby' => '\Predis\Commands\IncrementBy',
  1647. 'decr' => '\Predis\Commands\Decrement',
  1648. 'decrby' => '\Predis\Commands\DecrementBy',
  1649. 'exists' => '\Predis\Commands\Exists',
  1650. 'del' => '\Predis\Commands\Delete',
  1651. 'type' => '\Predis\Commands\Type',
  1652. /* commands operating on the key space */
  1653. 'keys' => '\Predis\Commands\Keys',
  1654. 'randomkey' => '\Predis\Commands\RandomKey',
  1655. 'rename' => '\Predis\Commands\Rename',
  1656. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1657. 'expire' => '\Predis\Commands\Expire',
  1658. 'expireat' => '\Predis\Commands\ExpireAt',
  1659. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1660. 'ttl' => '\Predis\Commands\TimeToLive',
  1661. /* commands operating on lists */
  1662. 'rpush' => '\Predis\Commands\ListPushTail',
  1663. 'lpush' => '\Predis\Commands\ListPushHead',
  1664. 'llen' => '\Predis\Commands\ListLength',
  1665. 'lrange' => '\Predis\Commands\ListRange',
  1666. 'ltrim' => '\Predis\Commands\ListTrim',
  1667. 'lindex' => '\Predis\Commands\ListIndex',
  1668. 'lset' => '\Predis\Commands\ListSet',
  1669. 'lrem' => '\Predis\Commands\ListRemove',
  1670. 'lpop' => '\Predis\Commands\ListPopFirst',
  1671. 'rpop' => '\Predis\Commands\ListPopLast',
  1672. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1673. /* commands operating on sets */
  1674. 'sadd' => '\Predis\Commands\SetAdd',
  1675. 'srem' => '\Predis\Commands\SetRemove',
  1676. 'spop' => '\Predis\Commands\SetPop',
  1677. 'smove' => '\Predis\Commands\SetMove',
  1678. 'scard' => '\Predis\Commands\SetCardinality',
  1679. 'sismember' => '\Predis\Commands\SetIsMember',
  1680. 'sinter' => '\Predis\Commands\SetIntersection',
  1681. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1682. 'sunion' => '\Predis\Commands\SetUnion',
  1683. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1684. 'sdiff' => '\Predis\Commands\SetDifference',
  1685. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1686. 'smembers' => '\Predis\Commands\SetMembers',
  1687. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1688. /* commands operating on sorted sets */
  1689. 'zadd' => '\Predis\Commands\ZSetAdd',
  1690. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1691. 'zrem' => '\Predis\Commands\ZSetRemove',
  1692. 'zrange' => '\Predis\Commands\ZSetRange',
  1693. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1694. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1695. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1696. 'zscore' => '\Predis\Commands\ZSetScore',
  1697. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1698. /* multiple databases handling commands */
  1699. 'select' => '\Predis\Commands\SelectDatabase',
  1700. 'move' => '\Predis\Commands\MoveKey',
  1701. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1702. 'flushall' => '\Predis\Commands\FlushAll',
  1703. /* sorting */
  1704. 'sort' => '\Predis\Commands\Sort',
  1705. /* remote server control commands */
  1706. 'info' => '\Predis\Commands\Info',
  1707. 'slaveof' => '\Predis\Commands\SlaveOf',
  1708. /* persistence control commands */
  1709. 'save' => '\Predis\Commands\Save',
  1710. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1711. 'lastsave' => '\Predis\Commands\LastSave',
  1712. 'shutdown' => '\Predis\Commands\Shutdown',
  1713. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1714. /* ---------------- Redis 2.0 ---------------- */
  1715. /* transactions */
  1716. 'multi' => '\Predis\Commands\Multi',
  1717. 'exec' => '\Predis\Commands\Exec',
  1718. 'discard' => '\Predis\Commands\Discard',
  1719. /* commands operating on string values */
  1720. 'setex' => '\Predis\Commands\SetExpire',
  1721. 'append' => '\Predis\Commands\Append',
  1722. 'substr' => '\Predis\Commands\Substr',
  1723. /* commands operating on lists */
  1724. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1725. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1726. /* commands operating on sorted sets */
  1727. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1728. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1729. 'zcount' => '\Predis\Commands\ZSetCount',
  1730. 'zrank' => '\Predis\Commands\ZSetRank',
  1731. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1732. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1733. /* commands operating on hashes */
  1734. 'hset' => '\Predis\Commands\HashSet',
  1735. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1736. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1737. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1738. 'hget' => '\Predis\Commands\HashGet',
  1739. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1740. 'hdel' => '\Predis\Commands\HashDelete',
  1741. 'hexists' => '\Predis\Commands\HashExists',
  1742. 'hlen' => '\Predis\Commands\HashLength',
  1743. 'hkeys' => '\Predis\Commands\HashKeys',
  1744. 'hvals' => '\Predis\Commands\HashValues',
  1745. 'hgetall' => '\Predis\Commands\HashGetAll',
  1746. /* publish - subscribe */
  1747. 'subscribe' => '\Predis\Commands\Subscribe',
  1748. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1749. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1750. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1751. 'publish' => '\Predis\Commands\Publish',
  1752. /* remote server control commands */
  1753. 'config' => '\Predis\Commands\Config',
  1754. );
  1755. }
  1756. }
  1757. class RedisServer_v2_2 extends RedisServerProfile {
  1758. public function getVersion() { return '2.2'; }
  1759. public function getSupportedCommands() {
  1760. return array(
  1761. /* ---------------- Redis 1.2 ---------------- */
  1762. /* miscellaneous commands */
  1763. 'ping' => '\Predis\Commands\Ping',
  1764. 'echo' => '\Predis\Commands\DoEcho',
  1765. 'auth' => '\Predis\Commands\Auth',
  1766. /* connection handling */
  1767. 'quit' => '\Predis\Commands\Quit',
  1768. /* commands operating on string values */
  1769. 'set' => '\Predis\Commands\Set',
  1770. 'setnx' => '\Predis\Commands\SetPreserve',
  1771. 'mset' => '\Predis\Commands\SetMultiple',
  1772. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1773. 'get' => '\Predis\Commands\Get',
  1774. 'mget' => '\Predis\Commands\GetMultiple',
  1775. 'getset' => '\Predis\Commands\GetSet',
  1776. 'incr' => '\Predis\Commands\Increment',
  1777. 'incrby' => '\Predis\Commands\IncrementBy',
  1778. 'decr' => '\Predis\Commands\Decrement',
  1779. 'decrby' => '\Predis\Commands\DecrementBy',
  1780. 'exists' => '\Predis\Commands\Exists',
  1781. 'del' => '\Predis\Commands\Delete',
  1782. 'type' => '\Predis\Commands\Type',
  1783. /* commands operating on the key space */
  1784. 'keys' => '\Predis\Commands\Keys',
  1785. 'randomkey' => '\Predis\Commands\RandomKey',
  1786. 'rename' => '\Predis\Commands\Rename',
  1787. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1788. 'expire' => '\Predis\Commands\Expire',
  1789. 'expireat' => '\Predis\Commands\ExpireAt',
  1790. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1791. 'ttl' => '\Predis\Commands\TimeToLive',
  1792. /* commands operating on lists */
  1793. 'rpush' => '\Predis\Commands\ListPushTail',
  1794. 'lpush' => '\Predis\Commands\ListPushHead',
  1795. 'llen' => '\Predis\Commands\ListLength',
  1796. 'lrange' => '\Predis\Commands\ListRange',
  1797. 'ltrim' => '\Predis\Commands\ListTrim',
  1798. 'lindex' => '\Predis\Commands\ListIndex',
  1799. 'lset' => '\Predis\Commands\ListSet',
  1800. 'lrem' => '\Predis\Commands\ListRemove',
  1801. 'lpop' => '\Predis\Commands\ListPopFirst',
  1802. 'rpop' => '\Predis\Commands\ListPopLast',
  1803. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1804. /* commands operating on sets */
  1805. 'sadd' => '\Predis\Commands\SetAdd',
  1806. 'srem' => '\Predis\Commands\SetRemove',
  1807. 'spop' => '\Predis\Commands\SetPop',
  1808. 'smove' => '\Predis\Commands\SetMove',
  1809. 'scard' => '\Predis\Commands\SetCardinality',
  1810. 'sismember' => '\Predis\Commands\SetIsMember',
  1811. 'sinter' => '\Predis\Commands\SetIntersection',
  1812. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1813. 'sunion' => '\Predis\Commands\SetUnion',
  1814. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1815. 'sdiff' => '\Predis\Commands\SetDifference',
  1816. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1817. 'smembers' => '\Predis\Commands\SetMembers',
  1818. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1819. /* commands operating on sorted sets */
  1820. 'zadd' => '\Predis\Commands\ZSetAdd',
  1821. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1822. 'zrem' => '\Predis\Commands\ZSetRemove',
  1823. 'zrange' => '\Predis\Commands\ZSetRange',
  1824. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1825. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1826. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1827. 'zscore' => '\Predis\Commands\ZSetScore',
  1828. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1829. /* multiple databases handling commands */
  1830. 'select' => '\Predis\Commands\SelectDatabase',
  1831. 'move' => '\Predis\Commands\MoveKey',
  1832. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1833. 'flushall' => '\Predis\Commands\FlushAll',
  1834. /* sorting */
  1835. 'sort' => '\Predis\Commands\Sort',
  1836. /* remote server control commands */
  1837. 'info' => '\Predis\Commands\Info',
  1838. 'slaveof' => '\Predis\Commands\SlaveOf',
  1839. /* persistence control commands */
  1840. 'save' => '\Predis\Commands\Save',
  1841. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1842. 'lastsave' => '\Predis\Commands\LastSave',
  1843. 'shutdown' => '\Predis\Commands\Shutdown',
  1844. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1845. /* ---------------- Redis 2.0 ---------------- */
  1846. /* transactions */
  1847. 'multi' => '\Predis\Commands\Multi',
  1848. 'exec' => '\Predis\Commands\Exec',
  1849. 'discard' => '\Predis\Commands\Discard',
  1850. /* commands operating on string values */
  1851. 'setex' => '\Predis\Commands\SetExpire',
  1852. 'append' => '\Predis\Commands\Append',
  1853. 'substr' => '\Predis\Commands\Substr',
  1854. /* commands operating on lists */
  1855. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1856. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1857. /* commands operating on sorted sets */
  1858. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1859. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1860. 'zcount' => '\Predis\Commands\ZSetCount',
  1861. 'zrank' => '\Predis\Commands\ZSetRank',
  1862. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1863. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1864. /* commands operating on hashes */
  1865. 'hset' => '\Predis\Commands\HashSet',
  1866. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1867. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1868. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1869. 'hget' => '\Predis\Commands\HashGet',
  1870. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1871. 'hdel' => '\Predis\Commands\HashDelete',
  1872. 'hexists' => '\Predis\Commands\HashExists',
  1873. 'hlen' => '\Predis\Commands\HashLength',
  1874. 'hkeys' => '\Predis\Commands\HashKeys',
  1875. 'hvals' => '\Predis\Commands\HashValues',
  1876. 'hgetall' => '\Predis\Commands\HashGetAll',
  1877. /* publish - subscribe */
  1878. 'subscribe' => '\Predis\Commands\Subscribe',
  1879. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1880. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1881. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1882. 'publish' => '\Predis\Commands\Publish',
  1883. /* remote server control commands */
  1884. 'config' => '\Predis\Commands\Config',
  1885. /* ---------------- Redis 2.2 ---------------- */
  1886. /* transactions */
  1887. 'watch' => '\Predis\Commands\Watch',
  1888. 'unwatch' => '\Predis\Commands\Unwatch',
  1889. /* commands operating on string values */
  1890. 'strlen' => '\Predis\Commands\Strlen',
  1891. 'setrange' => '\Predis\Commands\SetRange',
  1892. 'getrange' => '\Predis\Commands\Substr',
  1893. 'setbit' => '\Predis\Commands\SetBit',
  1894. 'getbit' => '\Predis\Commands\GetBit',
  1895. /* commands operating on the key space */
  1896. 'persist' => '\Predis\Commands\Persist',
  1897. /* commands operating on lists */
  1898. 'rpushx' => '\Predis\Commands\ListPushTailX',
  1899. 'lpushx' => '\Predis\Commands\ListPushHeadX',
  1900. 'linsert' => '\Predis\Commands\ListInsert',
  1901. 'brpoplpush' => '\Predis\Commands\ListPopLastPushHeadBlocking',
  1902. /* commands operating on sorted sets */
  1903. 'zrevrangebyscore' => '\Predis\Commands\ZSetReverseRangeByScore',
  1904. );
  1905. }
  1906. }
  1907. class RedisServer_vNext extends RedisServer_v2_2 {
  1908. public function getVersion() { return 'DEV'; }
  1909. public function getSupportedCommands() {
  1910. return array_merge(parent::getSupportedCommands(), array(
  1911. /* remote server control commands */
  1912. 'info' => '\Predis\Commands\Info_v24',
  1913. ));
  1914. }
  1915. }
  1916. /* ------------------------------------------------------------------------- */
  1917. namespace Predis\Pipeline;
  1918. interface IPipelineExecutor {
  1919. public function execute(\Predis\IConnection $connection, &$commands);
  1920. }
  1921. class StandardExecutor implements IPipelineExecutor {
  1922. public function execute(\Predis\IConnection $connection, &$commands) {
  1923. $sizeofPipe = count($commands);
  1924. $values = array();
  1925. foreach ($commands as $command) {
  1926. $connection->writeCommand($command);
  1927. }
  1928. try {
  1929. for ($i = 0; $i < $sizeofPipe; $i++) {
  1930. $response = $connection->readResponse($commands[$i]);
  1931. $values[] = $response instanceof \Iterator
  1932. ? iterator_to_array($response)
  1933. : $response;
  1934. unset($commands[$i]);
  1935. }
  1936. }
  1937. catch (\Predis\ServerException $exception) {
  1938. // force disconnection to prevent protocol desynchronization
  1939. $connection->disconnect();
  1940. throw $exception;
  1941. }
  1942. return $values;
  1943. }
  1944. }
  1945. class SafeExecutor implements IPipelineExecutor {
  1946. public function execute(\Predis\IConnection $connection, &$commands) {
  1947. $sizeofPipe = count($commands);
  1948. $values = array();
  1949. foreach ($commands as $command) {
  1950. try {
  1951. $connection->writeCommand($command);
  1952. }
  1953. catch (\Predis\CommunicationException $exception) {
  1954. return array_fill(0, $sizeofPipe, $exception);
  1955. }
  1956. }
  1957. for ($i = 0; $i < $sizeofPipe; $i++) {
  1958. $command = $commands[$i];
  1959. unset($commands[$i]);
  1960. try {
  1961. $response = $connection->readResponse($command);
  1962. $values[] = ($response instanceof \Iterator
  1963. ? iterator_to_array($response)
  1964. : $response
  1965. );
  1966. }
  1967. catch (\Predis\ServerException $exception) {
  1968. $values[] = $exception->toResponseError();
  1969. }
  1970. catch (\Predis\CommunicationException $exception) {
  1971. $toAdd = count($commands) - count($values);
  1972. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1973. break;
  1974. }
  1975. }
  1976. return $values;
  1977. }
  1978. }
  1979. class SafeClusterExecutor implements IPipelineExecutor {
  1980. public function execute(\Predis\IConnection $connection, &$commands) {
  1981. $connectionExceptions = array();
  1982. $sizeofPipe = count($commands);
  1983. $values = array();
  1984. foreach ($commands as $command) {
  1985. $cmdConnection = $connection->getConnection($command);
  1986. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1987. continue;
  1988. }
  1989. try {
  1990. $cmdConnection->writeCommand($command);
  1991. }
  1992. catch (\Predis\CommunicationException $exception) {
  1993. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1994. }
  1995. }
  1996. for ($i = 0; $i < $sizeofPipe; $i++) {
  1997. $command = $commands[$i];
  1998. unset($commands[$i]);
  1999. $cmdConnection = $connection->getConnection($command);
  2000. $connectionObjectHash = spl_object_hash($cmdConnection);
  2001. if (isset($connectionExceptions[$connectionObjectHash])) {
  2002. $values[] = $connectionExceptions[$connectionObjectHash];
  2003. continue;
  2004. }
  2005. try {
  2006. $response = $cmdConnection->readResponse($command);
  2007. $values[] = ($response instanceof \Iterator
  2008. ? iterator_to_array($response)
  2009. : $response
  2010. );
  2011. }
  2012. catch (\Predis\ServerException $exception) {
  2013. $values[] = $exception->toResponseError();
  2014. }
  2015. catch (\Predis\CommunicationException $exception) {
  2016. $values[] = $exception;
  2017. $connectionExceptions[$connectionObjectHash] = $exception;
  2018. }
  2019. }
  2020. return $values;
  2021. }
  2022. }
  2023. /* ------------------------------------------------------------------------- */
  2024. namespace Predis\Distribution;
  2025. interface IDistributionStrategy {
  2026. public function add($node, $weight = null);
  2027. public function remove($node);
  2028. public function get($key);
  2029. public function generateKey($value);
  2030. }
  2031. class EmptyRingException extends \Exception { }
  2032. class HashRing implements IDistributionStrategy {
  2033. const DEFAULT_REPLICAS = 128;
  2034. const DEFAULT_WEIGHT = 100;
  2035. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  2036. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  2037. $this->_replicas = $replicas;
  2038. $this->_nodes = array();
  2039. }
  2040. public function add($node, $weight = null) {
  2041. // NOTE: in case of collisions in the hashes of the nodes, the node added
  2042. // last wins, thus the order in which nodes are added is significant.
  2043. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  2044. $this->reset();
  2045. }
  2046. public function remove($node) {
  2047. // NOTE: a node is removed by resetting the ring so that it's recreated from
  2048. // scratch, in order to reassign possible hashes with collisions to the
  2049. // right node according to the order in which they were added in the
  2050. // first place.
  2051. for ($i = 0; $i < count($this->_nodes); ++$i) {
  2052. if ($this->_nodes[$i]['object'] === $node) {
  2053. array_splice($this->_nodes, $i, 1);
  2054. $this->reset();
  2055. break;
  2056. }
  2057. }
  2058. }
  2059. private function reset() {
  2060. unset($this->_ring);
  2061. unset($this->_ringKeys);
  2062. unset($this->_ringKeysCount);
  2063. }
  2064. private function isInitialized() {
  2065. return isset($this->_ringKeys);
  2066. }
  2067. private function computeTotalWeight() {
  2068. // TODO: array_reduce + lambda for PHP 5.3
  2069. $totalWeight = 0;
  2070. foreach ($this->_nodes as $node) {
  2071. $totalWeight += $node['weight'];
  2072. }
  2073. return $totalWeight;
  2074. }
  2075. private function initialize() {
  2076. if ($this->isInitialized()) {
  2077. return;
  2078. }
  2079. if (count($this->_nodes) === 0) {
  2080. throw new EmptyRingException('Cannot initialize empty hashring');
  2081. }
  2082. $this->_ring = array();
  2083. $totalWeight = $this->computeTotalWeight();
  2084. $nodesCount = count($this->_nodes);
  2085. foreach ($this->_nodes as $node) {
  2086. $weightRatio = $node['weight'] / $totalWeight;
  2087. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  2088. }
  2089. ksort($this->_ring, SORT_NUMERIC);
  2090. $this->_ringKeys = array_keys($this->_ring);
  2091. $this->_ringKeysCount = count($this->_ringKeys);
  2092. }
  2093. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  2094. $nodeObject = $node['object'];
  2095. $nodeHash = (string) $nodeObject;
  2096. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  2097. for ($i = 0; $i < $replicas; $i++) {
  2098. $key = crc32("$nodeHash:$i");
  2099. $ring[$key] = $nodeObject;
  2100. }
  2101. }
  2102. public function generateKey($value) {
  2103. return crc32($value);
  2104. }
  2105. public function get($key) {
  2106. return $this->_ring[$this->getNodeKey($key)];
  2107. }
  2108. private function getNodeKey($key) {
  2109. $this->initialize();
  2110. $ringKeys = $this->_ringKeys;
  2111. $upper = $this->_ringKeysCount - 1;
  2112. $lower = 0;
  2113. while ($lower <= $upper) {
  2114. $index = ($lower + $upper) >> 1;
  2115. $item = $ringKeys[$index];
  2116. if ($item > $key) {
  2117. $upper = $index - 1;
  2118. }
  2119. else if ($item < $key) {
  2120. $lower = $index + 1;
  2121. }
  2122. else {
  2123. return $item;
  2124. }
  2125. }
  2126. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  2127. }
  2128. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  2129. // NOTE: binary search for the last item in _ringkeys with a value
  2130. // less or equal to the key. If no such item exists, return the
  2131. // last item.
  2132. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  2133. }
  2134. }
  2135. class KetamaPureRing extends HashRing {
  2136. const DEFAULT_REPLICAS = 160;
  2137. public function __construct() {
  2138. parent::__construct($this::DEFAULT_REPLICAS);
  2139. }
  2140. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  2141. $nodeObject = $node['object'];
  2142. $nodeHash = (string) $nodeObject;
  2143. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  2144. for ($i = 0; $i < $replicas; $i++) {
  2145. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  2146. foreach ($unpackedDigest as $key) {
  2147. $ring[$key] = $nodeObject;
  2148. }
  2149. }
  2150. }
  2151. public function generateKey($value) {
  2152. $hash = unpack('V', md5($value, true));
  2153. return $hash[1];
  2154. }
  2155. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  2156. // NOTE: binary search for the first item in _ringkeys with a value
  2157. // greater or equal to the key. If no such item exists, return the
  2158. // first item.
  2159. return $lower < $ringKeysCount ? $lower : 0;
  2160. }
  2161. }
  2162. /* ------------------------------------------------------------------------- */
  2163. namespace Predis\Shared;
  2164. class Utils {
  2165. public static function isCluster(\Predis\IConnection $connection) {
  2166. return $connection instanceof \Predis\ConnectionCluster;
  2167. }
  2168. public static function onCommunicationException(\Predis\CommunicationException $exception) {
  2169. if ($exception->shouldResetConnection()) {
  2170. $connection = $exception->getConnection();
  2171. if ($connection->isConnected()) {
  2172. $connection->disconnect();
  2173. }
  2174. }
  2175. throw $exception;
  2176. }
  2177. public static function filterArrayArguments(Array $arguments) {
  2178. if (count($arguments) === 1 && is_array($arguments[0])) {
  2179. return $arguments[0];
  2180. }
  2181. return $arguments;
  2182. }
  2183. }
  2184. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  2185. protected $_position, $_current, $_replySize;
  2186. public function rewind() {
  2187. // NOOP
  2188. }
  2189. public function current() {
  2190. return $this->_current;
  2191. }
  2192. public function key() {
  2193. return $this->_position;
  2194. }
  2195. public function next() {
  2196. if (++$this->_position < $this->_replySize) {
  2197. $this->_current = $this->getValue();
  2198. }
  2199. return $this->_position;
  2200. }
  2201. public function valid() {
  2202. return $this->_position < $this->_replySize;
  2203. }
  2204. public function count() {
  2205. // NOTE: use count if you want to get the size of the current multi-bulk
  2206. // response without using iterator_count (which actually consumes
  2207. // our iterator to calculate the size, and we cannot perform a rewind)
  2208. return $this->_replySize;
  2209. }
  2210. protected abstract function getValue();
  2211. }
  2212. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  2213. private $_connection;
  2214. public function __construct(\Predis\Connection $connection, $size) {
  2215. $this->_connection = $connection;
  2216. $this->_reader = $connection->getResponseReader();
  2217. $this->_position = 0;
  2218. $this->_current = $size > 0 ? $this->getValue() : null;
  2219. $this->_replySize = $size;
  2220. }
  2221. public function __destruct() {
  2222. // when the iterator is garbage-collected (e.g. it goes out of the
  2223. // scope of a foreach) but it has not reached its end, we must sync
  2224. // the client with the queued elements that have not been read from
  2225. // the connection with the server.
  2226. $this->sync();
  2227. }
  2228. public function sync($drop = false) {
  2229. if ($drop == true) {
  2230. if ($this->valid()) {
  2231. $this->_position = $this->_replySize;
  2232. $this->_connection->disconnect();
  2233. }
  2234. }
  2235. else {
  2236. while ($this->valid()) {
  2237. $this->next();
  2238. }
  2239. }
  2240. }
  2241. protected function getValue() {
  2242. return $this->_reader->read($this->_connection);
  2243. }
  2244. }
  2245. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  2246. private $_iterator;
  2247. public function __construct(MultiBulkResponseIterator $iterator) {
  2248. $virtualSize = count($iterator) / 2;
  2249. $this->_iterator = $iterator;
  2250. $this->_position = 0;
  2251. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  2252. $this->_replySize = $virtualSize;
  2253. }
  2254. public function __destruct() {
  2255. $this->_iterator->sync();
  2256. }
  2257. protected function getValue() {
  2258. $k = $this->_iterator->current();
  2259. $this->_iterator->next();
  2260. $v = $this->_iterator->current();
  2261. $this->_iterator->next();
  2262. return array($k, $v);
  2263. }
  2264. }
  2265. /* ------------------------------------------------------------------------- */
  2266. namespace Predis\Commands;
  2267. /* miscellaneous commands */
  2268. class Ping extends \Predis\MultiBulkCommand {
  2269. public function canBeHashed() { return false; }
  2270. public function getCommandId() { return 'PING'; }
  2271. public function parseResponse($data) {
  2272. return $data === 'PONG';
  2273. }
  2274. }
  2275. class DoEcho extends \Predis\MultiBulkCommand {
  2276. public function canBeHashed() { return false; }
  2277. public function getCommandId() { return 'ECHO'; }
  2278. }
  2279. class Auth extends \Predis\MultiBulkCommand {
  2280. public function canBeHashed() { return false; }
  2281. public function getCommandId() { return 'AUTH'; }
  2282. }
  2283. /* connection handling */
  2284. class Quit extends \Predis\MultiBulkCommand {
  2285. public function canBeHashed() { return false; }
  2286. public function getCommandId() { return 'QUIT'; }
  2287. public function closesConnection() { return true; }
  2288. }
  2289. /* commands operating on string values */
  2290. class Set extends \Predis\MultiBulkCommand {
  2291. public function getCommandId() { return 'SET'; }
  2292. }
  2293. class SetExpire extends \Predis\MultiBulkCommand {
  2294. public function getCommandId() { return 'SETEX'; }
  2295. }
  2296. class SetPreserve extends \Predis\MultiBulkCommand {
  2297. public function getCommandId() { return 'SETNX'; }
  2298. public function parseResponse($data) { return (bool) $data; }
  2299. }
  2300. class SetMultiple extends \Predis\MultiBulkCommand {
  2301. public function canBeHashed() { return false; }
  2302. public function getCommandId() { return 'MSET'; }
  2303. public function filterArguments(Array $arguments) {
  2304. if (count($arguments) === 1 && is_array($arguments[0])) {
  2305. $flattenedKVs = array();
  2306. $args = &$arguments[0];
  2307. foreach ($args as $k => $v) {
  2308. $flattenedKVs[] = $k;
  2309. $flattenedKVs[] = $v;
  2310. }
  2311. return $flattenedKVs;
  2312. }
  2313. return $arguments;
  2314. }
  2315. }
  2316. class SetMultiplePreserve extends \Predis\Commands\SetMultiple {
  2317. public function canBeHashed() { return false; }
  2318. public function getCommandId() { return 'MSETNX'; }
  2319. public function parseResponse($data) { return (bool) $data; }
  2320. }
  2321. class Get extends \Predis\MultiBulkCommand {
  2322. public function getCommandId() { return 'GET'; }
  2323. }
  2324. class GetMultiple extends \Predis\MultiBulkCommand {
  2325. public function canBeHashed() { return false; }
  2326. public function getCommandId() { return 'MGET'; }
  2327. public function filterArguments(Array $arguments) {
  2328. return \Predis\Shared\Utils::filterArrayArguments($arguments);
  2329. }
  2330. }
  2331. class GetSet extends \Predis\MultiBulkCommand {
  2332. public function getCommandId() { return 'GETSET'; }
  2333. }
  2334. class Increment extends \Predis\MultiBulkCommand {
  2335. public function getCommandId() { return 'INCR'; }
  2336. }
  2337. class IncrementBy extends \Predis\MultiBulkCommand {
  2338. public function getCommandId() { return 'INCRBY'; }
  2339. }
  2340. class Decrement extends \Predis\MultiBulkCommand {
  2341. public function getCommandId() { return 'DECR'; }
  2342. }
  2343. class DecrementBy extends \Predis\MultiBulkCommand {
  2344. public function getCommandId() { return 'DECRBY'; }
  2345. }
  2346. class Exists extends \Predis\MultiBulkCommand {
  2347. public function getCommandId() { return 'EXISTS'; }
  2348. public function parseResponse($data) { return (bool) $data; }
  2349. }
  2350. class Delete extends \Predis\MultiBulkCommand {
  2351. public function getCommandId() { return 'DEL'; }
  2352. }
  2353. class Type extends \Predis\MultiBulkCommand {
  2354. public function getCommandId() { return 'TYPE'; }
  2355. }
  2356. class Append extends \Predis\MultiBulkCommand {
  2357. public function getCommandId() { return 'APPEND'; }
  2358. }
  2359. class SetRange extends \Predis\MultiBulkCommand {
  2360. public function getCommandId() { return 'SETRANGE'; }
  2361. }
  2362. class Substr extends \Predis\MultiBulkCommand {
  2363. public function getCommandId() { return 'SUBSTR'; }
  2364. }
  2365. class SetBit extends \Predis\MultiBulkCommand {
  2366. public function getCommandId() { return 'SETBIT'; }
  2367. }
  2368. class GetBit extends \Predis\MultiBulkCommand {
  2369. public function getCommandId() { return 'GETBIT'; }
  2370. }
  2371. class Strlen extends \Predis\MultiBulkCommand {
  2372. public function getCommandId() { return 'STRLEN'; }
  2373. }
  2374. /* commands operating on the key space */
  2375. class Keys extends \Predis\MultiBulkCommand {
  2376. public function canBeHashed() { return false; }
  2377. public function getCommandId() { return 'KEYS'; }
  2378. }
  2379. class Keys_v1_2 extends Keys {
  2380. public function parseResponse($data) {
  2381. return explode(' ', $data);
  2382. }
  2383. }
  2384. class RandomKey extends \Predis\MultiBulkCommand {
  2385. public function canBeHashed() { return false; }
  2386. public function getCommandId() { return 'RANDOMKEY'; }
  2387. public function parseResponse($data) { return $data !== '' ? $data : null; }
  2388. }
  2389. class Rename extends \Predis\MultiBulkCommand {
  2390. public function canBeHashed() { return false; }
  2391. public function getCommandId() { return 'RENAME'; }
  2392. }
  2393. class RenamePreserve extends \Predis\MultiBulkCommand {
  2394. public function canBeHashed() { return false; }
  2395. public function getCommandId() { return 'RENAMENX'; }
  2396. public function parseResponse($data) { return (bool) $data; }
  2397. }
  2398. class Expire extends \Predis\MultiBulkCommand {
  2399. public function getCommandId() { return 'EXPIRE'; }
  2400. public function parseResponse($data) { return (bool) $data; }
  2401. }
  2402. class ExpireAt extends \Predis\MultiBulkCommand {
  2403. public function getCommandId() { return 'EXPIREAT'; }
  2404. public function parseResponse($data) { return (bool) $data; }
  2405. }
  2406. class Persist extends \Predis\MultiBulkCommand {
  2407. public function getCommandId() { return 'PERSIST'; }
  2408. public function parseResponse($data) { return (bool) $data; }
  2409. }
  2410. class DatabaseSize extends \Predis\MultiBulkCommand {
  2411. public function canBeHashed() { return false; }
  2412. public function getCommandId() { return 'DBSIZE'; }
  2413. }
  2414. class TimeToLive extends \Predis\MultiBulkCommand {
  2415. public function getCommandId() { return 'TTL'; }
  2416. }
  2417. /* commands operating on lists */
  2418. class ListPushTail extends \Predis\MultiBulkCommand {
  2419. public function getCommandId() { return 'RPUSH'; }
  2420. }
  2421. class ListPushTailX extends \Predis\MultiBulkCommand {
  2422. public function getCommandId() { return 'RPUSHX'; }
  2423. }
  2424. class ListPushHead extends \Predis\MultiBulkCommand {
  2425. public function getCommandId() { return 'LPUSH'; }
  2426. }
  2427. class ListPushHeadX extends \Predis\MultiBulkCommand {
  2428. public function getCommandId() { return 'LPUSHX'; }
  2429. }
  2430. class ListLength extends \Predis\MultiBulkCommand {
  2431. public function getCommandId() { return 'LLEN'; }
  2432. }
  2433. class ListRange extends \Predis\MultiBulkCommand {
  2434. public function getCommandId() { return 'LRANGE'; }
  2435. }
  2436. class ListTrim extends \Predis\MultiBulkCommand {
  2437. public function getCommandId() { return 'LTRIM'; }
  2438. }
  2439. class ListIndex extends \Predis\MultiBulkCommand {
  2440. public function getCommandId() { return 'LINDEX'; }
  2441. }
  2442. class ListSet extends \Predis\MultiBulkCommand {
  2443. public function getCommandId() { return 'LSET'; }
  2444. }
  2445. class ListRemove extends \Predis\MultiBulkCommand {
  2446. public function getCommandId() { return 'LREM'; }
  2447. }
  2448. class ListPopLastPushHead extends \Predis\MultiBulkCommand {
  2449. public function getCommandId() { return 'RPOPLPUSH'; }
  2450. }
  2451. class ListPopLastPushHeadBlocking extends \Predis\MultiBulkCommand {
  2452. public function getCommandId() { return 'BRPOPLPUSH'; }
  2453. }
  2454. class ListPopFirst extends \Predis\MultiBulkCommand {
  2455. public function getCommandId() { return 'LPOP'; }
  2456. }
  2457. class ListPopLast extends \Predis\MultiBulkCommand {
  2458. public function getCommandId() { return 'RPOP'; }
  2459. }
  2460. class ListPopFirstBlocking extends \Predis\MultiBulkCommand {
  2461. public function getCommandId() { return 'BLPOP'; }
  2462. }
  2463. class ListPopLastBlocking extends \Predis\MultiBulkCommand {
  2464. public function getCommandId() { return 'BRPOP'; }
  2465. }
  2466. class ListInsert extends \Predis\MultiBulkCommand {
  2467. public function getCommandId() { return 'LINSERT'; }
  2468. }
  2469. /* commands operating on sets */
  2470. class SetAdd extends \Predis\MultiBulkCommand {
  2471. public function getCommandId() { return 'SADD'; }
  2472. public function parseResponse($data) { return (bool) $data; }
  2473. }
  2474. class SetRemove extends \Predis\MultiBulkCommand {
  2475. public function getCommandId() { return 'SREM'; }
  2476. public function parseResponse($data) { return (bool) $data; }
  2477. }
  2478. class SetPop extends \Predis\MultiBulkCommand {
  2479. public function getCommandId() { return 'SPOP'; }
  2480. }
  2481. class SetMove extends \Predis\MultiBulkCommand {
  2482. public function canBeHashed() { return false; }
  2483. public function getCommandId() { return 'SMOVE'; }
  2484. public function parseResponse($data) { return (bool) $data; }
  2485. }
  2486. class SetCardinality extends \Predis\MultiBulkCommand {
  2487. public function getCommandId() { return 'SCARD'; }
  2488. }
  2489. class SetIsMember extends \Predis\MultiBulkCommand {
  2490. public function getCommandId() { return 'SISMEMBER'; }
  2491. public function parseResponse($data) { return (bool) $data; }
  2492. }
  2493. class SetIntersection extends \Predis\MultiBulkCommand {
  2494. public function getCommandId() { return 'SINTER'; }
  2495. public function filterArguments(Array $arguments) {
  2496. return \Predis\Shared\Utils::filterArrayArguments($arguments);
  2497. }
  2498. }
  2499. class SetIntersectionStore extends \Predis\MultiBulkCommand {
  2500. public function getCommandId() { return 'SINTERSTORE'; }
  2501. public function filterArguments(Array $arguments) {
  2502. if (count($arguments) === 2 && is_array($arguments[1])) {
  2503. return array_merge(array($arguments[0]), $arguments[1]);
  2504. }
  2505. return $arguments;
  2506. }
  2507. }
  2508. class SetUnion extends \Predis\Commands\SetIntersection {
  2509. public function getCommandId() { return 'SUNION'; }
  2510. }
  2511. class SetUnionStore extends \Predis\Commands\SetIntersectionStore {
  2512. public function getCommandId() { return 'SUNIONSTORE'; }
  2513. }
  2514. class SetDifference extends \Predis\MultiBulkCommand {
  2515. public function getCommandId() { return 'SDIFF'; }
  2516. }
  2517. class SetDifferenceStore extends \Predis\Commands\SetIntersectionStore {
  2518. public function getCommandId() { return 'SDIFFSTORE'; }
  2519. }
  2520. class SetMembers extends \Predis\MultiBulkCommand {
  2521. public function getCommandId() { return 'SMEMBERS'; }
  2522. }
  2523. class SetRandomMember extends \Predis\MultiBulkCommand {
  2524. public function getCommandId() { return 'SRANDMEMBER'; }
  2525. }
  2526. /* commands operating on sorted sets */
  2527. class ZSetAdd extends \Predis\MultiBulkCommand {
  2528. public function getCommandId() { return 'ZADD'; }
  2529. public function parseResponse($data) { return (bool) $data; }
  2530. }
  2531. class ZSetIncrementBy extends \Predis\MultiBulkCommand {
  2532. public function getCommandId() { return 'ZINCRBY'; }
  2533. }
  2534. class ZSetRemove extends \Predis\MultiBulkCommand {
  2535. public function getCommandId() { return 'ZREM'; }
  2536. public function parseResponse($data) { return (bool) $data; }
  2537. }
  2538. class ZSetUnionStore extends \Predis\MultiBulkCommand {
  2539. public function getCommandId() { return 'ZUNIONSTORE'; }
  2540. public function filterArguments(Array $arguments) {
  2541. $options = array();
  2542. $argc = count($arguments);
  2543. if ($argc > 2 && is_array($arguments[$argc - 1])) {
  2544. $options = $this->prepareOptions(array_pop($arguments));
  2545. }
  2546. if (is_array($arguments[1])) {
  2547. $arguments = array_merge(
  2548. array($arguments[0], count($arguments[1])),
  2549. $arguments[1]
  2550. );
  2551. }
  2552. return array_merge($arguments, $options);
  2553. }
  2554. private function prepareOptions($options) {
  2555. $opts = array_change_key_case($options, CASE_UPPER);
  2556. $finalizedOpts = array();
  2557. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2558. $finalizedOpts[] = 'WEIGHTS';
  2559. foreach ($opts['WEIGHTS'] as $weight) {
  2560. $finalizedOpts[] = $weight;
  2561. }
  2562. }
  2563. if (isset($opts['AGGREGATE'])) {
  2564. $finalizedOpts[] = 'AGGREGATE';
  2565. $finalizedOpts[] = $opts['AGGREGATE'];
  2566. }
  2567. return $finalizedOpts;
  2568. }
  2569. }
  2570. class ZSetIntersectionStore extends \Predis\Commands\ZSetUnionStore {
  2571. public function getCommandId() { return 'ZINTERSTORE'; }
  2572. }
  2573. class ZSetRange extends \Predis\MultiBulkCommand {
  2574. private $_withScores = false;
  2575. public function getCommandId() { return 'ZRANGE'; }
  2576. public function filterArguments(Array $arguments) {
  2577. if (count($arguments) === 4) {
  2578. $lastType = gettype($arguments[3]);
  2579. if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') {
  2580. // used for compatibility with older versions
  2581. $arguments[3] = array('WITHSCORES' => true);
  2582. $lastType = 'array';
  2583. }
  2584. if ($lastType === 'array') {
  2585. $options = $this->prepareOptions(array_pop($arguments));
  2586. return array_merge($arguments, $options);
  2587. }
  2588. }
  2589. return $arguments;
  2590. }
  2591. protected function prepareOptions($options) {
  2592. $opts = array_change_key_case($options, CASE_UPPER);
  2593. $finalizedOpts = array();
  2594. if (isset($opts['WITHSCORES'])) {
  2595. $finalizedOpts[] = 'WITHSCORES';
  2596. $this->_withScores = true;
  2597. }
  2598. return $finalizedOpts;
  2599. }
  2600. public function parseResponse($data) {
  2601. if ($this->_withScores) {
  2602. if ($data instanceof \Iterator) {
  2603. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2604. }
  2605. $result = array();
  2606. for ($i = 0; $i < count($data); $i++) {
  2607. $result[] = array($data[$i], $data[++$i]);
  2608. }
  2609. return $result;
  2610. }
  2611. return $data;
  2612. }
  2613. }
  2614. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  2615. public function getCommandId() { return 'ZREVRANGE'; }
  2616. }
  2617. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  2618. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2619. protected function prepareOptions($options) {
  2620. $opts = array_change_key_case($options, CASE_UPPER);
  2621. $finalizedOpts = array();
  2622. if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) {
  2623. $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER);
  2624. $finalizedOpts[] = 'LIMIT';
  2625. $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0];
  2626. $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1];
  2627. }
  2628. return array_merge($finalizedOpts, parent::prepareOptions($options));
  2629. }
  2630. }
  2631. class ZSetReverseRangeByScore extends \Predis\Commands\ZSetRangeByScore {
  2632. public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
  2633. }
  2634. class ZSetCount extends \Predis\MultiBulkCommand {
  2635. public function getCommandId() { return 'ZCOUNT'; }
  2636. }
  2637. class ZSetCardinality extends \Predis\MultiBulkCommand {
  2638. public function getCommandId() { return 'ZCARD'; }
  2639. }
  2640. class ZSetScore extends \Predis\MultiBulkCommand {
  2641. public function getCommandId() { return 'ZSCORE'; }
  2642. }
  2643. class ZSetRemoveRangeByScore extends \Predis\MultiBulkCommand {
  2644. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2645. }
  2646. class ZSetRank extends \Predis\MultiBulkCommand {
  2647. public function getCommandId() { return 'ZRANK'; }
  2648. }
  2649. class ZSetReverseRank extends \Predis\MultiBulkCommand {
  2650. public function getCommandId() { return 'ZREVRANK'; }
  2651. }
  2652. class ZSetRemoveRangeByRank extends \Predis\MultiBulkCommand {
  2653. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2654. }
  2655. /* commands operating on hashes */
  2656. class HashSet extends \Predis\MultiBulkCommand {
  2657. public function getCommandId() { return 'HSET'; }
  2658. public function parseResponse($data) { return (bool) $data; }
  2659. }
  2660. class HashSetPreserve extends \Predis\MultiBulkCommand {
  2661. public function getCommandId() { return 'HSETNX'; }
  2662. public function parseResponse($data) { return (bool) $data; }
  2663. }
  2664. class HashSetMultiple extends \Predis\MultiBulkCommand {
  2665. public function getCommandId() { return 'HMSET'; }
  2666. public function filterArguments(Array $arguments) {
  2667. if (count($arguments) === 2 && is_array($arguments[1])) {
  2668. $flattenedKVs = array($arguments[0]);
  2669. $args = &$arguments[1];
  2670. foreach ($args as $k => $v) {
  2671. $flattenedKVs[] = $k;
  2672. $flattenedKVs[] = $v;
  2673. }
  2674. return $flattenedKVs;
  2675. }
  2676. return $arguments;
  2677. }
  2678. }
  2679. class HashIncrementBy extends \Predis\MultiBulkCommand {
  2680. public function getCommandId() { return 'HINCRBY'; }
  2681. }
  2682. class HashGet extends \Predis\MultiBulkCommand {
  2683. public function getCommandId() { return 'HGET'; }
  2684. }
  2685. class HashGetMultiple extends \Predis\MultiBulkCommand {
  2686. public function getCommandId() { return 'HMGET'; }
  2687. public function filterArguments(Array $arguments) {
  2688. if (count($arguments) === 2 && is_array($arguments[1])) {
  2689. $flattenedKVs = array($arguments[0]);
  2690. $args = &$arguments[1];
  2691. foreach ($args as $v) {
  2692. $flattenedKVs[] = $v;
  2693. }
  2694. return $flattenedKVs;
  2695. }
  2696. return $arguments;
  2697. }
  2698. }
  2699. class HashDelete extends \Predis\MultiBulkCommand {
  2700. public function getCommandId() { return 'HDEL'; }
  2701. public function parseResponse($data) { return (bool) $data; }
  2702. }
  2703. class HashExists extends \Predis\MultiBulkCommand {
  2704. public function getCommandId() { return 'HEXISTS'; }
  2705. public function parseResponse($data) { return (bool) $data; }
  2706. }
  2707. class HashLength extends \Predis\MultiBulkCommand {
  2708. public function getCommandId() { return 'HLEN'; }
  2709. }
  2710. class HashKeys extends \Predis\MultiBulkCommand {
  2711. public function getCommandId() { return 'HKEYS'; }
  2712. }
  2713. class HashValues extends \Predis\MultiBulkCommand {
  2714. public function getCommandId() { return 'HVALS'; }
  2715. }
  2716. class HashGetAll extends \Predis\MultiBulkCommand {
  2717. public function getCommandId() { return 'HGETALL'; }
  2718. public function parseResponse($data) {
  2719. if ($data instanceof \Iterator) {
  2720. return new \Predis\Shared\MultiBulkResponseKVIterator($data);
  2721. }
  2722. $result = array();
  2723. for ($i = 0; $i < count($data); $i++) {
  2724. $result[$data[$i]] = $data[++$i];
  2725. }
  2726. return $result;
  2727. }
  2728. }
  2729. /* multiple databases handling commands */
  2730. class SelectDatabase extends \Predis\MultiBulkCommand {
  2731. public function canBeHashed() { return false; }
  2732. public function getCommandId() { return 'SELECT'; }
  2733. }
  2734. class MoveKey extends \Predis\MultiBulkCommand {
  2735. public function canBeHashed() { return false; }
  2736. public function getCommandId() { return 'MOVE'; }
  2737. public function parseResponse($data) { return (bool) $data; }
  2738. }
  2739. class FlushDatabase extends \Predis\MultiBulkCommand {
  2740. public function canBeHashed() { return false; }
  2741. public function getCommandId() { return 'FLUSHDB'; }
  2742. }
  2743. class FlushAll extends \Predis\MultiBulkCommand {
  2744. public function canBeHashed() { return false; }
  2745. public function getCommandId() { return 'FLUSHALL'; }
  2746. }
  2747. /* sorting */
  2748. class Sort extends \Predis\MultiBulkCommand {
  2749. public function getCommandId() { return 'SORT'; }
  2750. public function filterArguments(Array $arguments) {
  2751. if (count($arguments) === 1) {
  2752. return $arguments;
  2753. }
  2754. $query = array($arguments[0]);
  2755. $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
  2756. if (isset($sortParams['BY'])) {
  2757. $query[] = 'BY';
  2758. $query[] = $sortParams['BY'];
  2759. }
  2760. if (isset($sortParams['GET'])) {
  2761. $getargs = $sortParams['GET'];
  2762. if (is_array($getargs)) {
  2763. foreach ($getargs as $getarg) {
  2764. $query[] = 'GET';
  2765. $query[] = $getarg;
  2766. }
  2767. }
  2768. else {
  2769. $query[] = 'GET';
  2770. $query[] = $getargs;
  2771. }
  2772. }
  2773. if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
  2774. && count($sortParams['LIMIT']) == 2) {
  2775. $query[] = 'LIMIT';
  2776. $query[] = $sortParams['LIMIT'][0];
  2777. $query[] = $sortParams['LIMIT'][1];
  2778. }
  2779. if (isset($sortParams['SORT'])) {
  2780. $query[] = strtoupper($sortParams['SORT']);
  2781. }
  2782. if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) {
  2783. $query[] = 'ALPHA';
  2784. }
  2785. if (isset($sortParams['STORE'])) {
  2786. $query[] = 'STORE';
  2787. $query[] = $sortParams['STORE'];
  2788. }
  2789. return $query;
  2790. }
  2791. }
  2792. /* transactions */
  2793. class Multi extends \Predis\MultiBulkCommand {
  2794. public function canBeHashed() { return false; }
  2795. public function getCommandId() { return 'MULTI'; }
  2796. }
  2797. class Exec extends \Predis\MultiBulkCommand {
  2798. public function canBeHashed() { return false; }
  2799. public function getCommandId() { return 'EXEC'; }
  2800. }
  2801. class Discard extends \Predis\MultiBulkCommand {
  2802. public function canBeHashed() { return false; }
  2803. public function getCommandId() { return 'DISCARD'; }
  2804. }
  2805. class Watch extends \Predis\MultiBulkCommand {
  2806. public function canBeHashed() { return false; }
  2807. public function getCommandId() { return 'WATCH'; }
  2808. public function filterArguments(Array $arguments) {
  2809. if (isset($arguments[0]) && is_array($arguments[0])) {
  2810. return $arguments[0];
  2811. }
  2812. return $arguments;
  2813. }
  2814. public function parseResponse($data) { return (bool) $data; }
  2815. }
  2816. class Unwatch extends \Predis\MultiBulkCommand {
  2817. public function canBeHashed() { return false; }
  2818. public function getCommandId() { return 'UNWATCH'; }
  2819. public function parseResponse($data) { return (bool) $data; }
  2820. }
  2821. /* publish/subscribe */
  2822. class Subscribe extends \Predis\MultiBulkCommand {
  2823. public function canBeHashed() { return false; }
  2824. public function getCommandId() { return 'SUBSCRIBE'; }
  2825. public function filterArguments(Array $arguments) {
  2826. return \Predis\Shared\Utils::filterArrayArguments($arguments);
  2827. }
  2828. }
  2829. class Unsubscribe extends \Predis\MultiBulkCommand {
  2830. public function canBeHashed() { return false; }
  2831. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2832. }
  2833. class SubscribeByPattern extends \Predis\MultiBulkCommand {
  2834. public function canBeHashed() { return false; }
  2835. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2836. public function filterArguments(Array $arguments) {
  2837. return \Predis\Shared\Utils::filterArrayArguments($arguments);
  2838. }
  2839. }
  2840. class UnsubscribeByPattern extends \Predis\MultiBulkCommand {
  2841. public function canBeHashed() { return false; }
  2842. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2843. }
  2844. class Publish extends \Predis\MultiBulkCommand {
  2845. public function canBeHashed() { return false; }
  2846. public function getCommandId() { return 'PUBLISH'; }
  2847. }
  2848. /* persistence control commands */
  2849. class Save extends \Predis\MultiBulkCommand {
  2850. public function canBeHashed() { return false; }
  2851. public function getCommandId() { return 'SAVE'; }
  2852. }
  2853. class BackgroundSave extends \Predis\MultiBulkCommand {
  2854. public function canBeHashed() { return false; }
  2855. public function getCommandId() { return 'BGSAVE'; }
  2856. public function parseResponse($data) {
  2857. if ($data == 'Background saving started') {
  2858. return true;
  2859. }
  2860. return $data;
  2861. }
  2862. }
  2863. class BackgroundRewriteAppendOnlyFile extends \Predis\MultiBulkCommand {
  2864. public function canBeHashed() { return false; }
  2865. public function getCommandId() { return 'BGREWRITEAOF'; }
  2866. public function parseResponse($data) {
  2867. return $data == 'Background append only file rewriting started';
  2868. }
  2869. }
  2870. class LastSave extends \Predis\MultiBulkCommand {
  2871. public function canBeHashed() { return false; }
  2872. public function getCommandId() { return 'LASTSAVE'; }
  2873. }
  2874. class Shutdown extends \Predis\MultiBulkCommand {
  2875. public function canBeHashed() { return false; }
  2876. public function getCommandId() { return 'SHUTDOWN'; }
  2877. public function closesConnection() { return true; }
  2878. }
  2879. /* remote server control commands */
  2880. class Info extends \Predis\MultiBulkCommand {
  2881. public function canBeHashed() { return false; }
  2882. public function getCommandId() { return 'INFO'; }
  2883. public function parseResponse($data) {
  2884. $info = array();
  2885. $infoLines = explode("\r\n", $data, -1);
  2886. foreach ($infoLines as $row) {
  2887. @list($k, $v) = explode(':', $row);
  2888. if ($row === '' || !isset($v)) {
  2889. continue;
  2890. }
  2891. if (!preg_match('/^db\d+$/', $k)) {
  2892. if ($k === 'allocation_stats') {
  2893. $info[$k] = $this->parseAllocationStats($v);
  2894. continue;
  2895. }
  2896. $info[$k] = $v;
  2897. }
  2898. else {
  2899. $info[$k] = $this->parseDatabaseStats($v);
  2900. }
  2901. }
  2902. return $info;
  2903. }
  2904. protected function parseDatabaseStats($str) {
  2905. $db = array();
  2906. foreach (explode(',', $str) as $dbvar) {
  2907. list($dbvk, $dbvv) = explode('=', $dbvar);
  2908. $db[trim($dbvk)] = $dbvv;
  2909. }
  2910. return $db;
  2911. }
  2912. protected function parseAllocationStats($str) {
  2913. $stats = array();
  2914. foreach (explode(',', $str) as $kv) {
  2915. @list($size, $objects, $extra) = explode('=', $kv);
  2916. // hack to prevent incorrect values when parsing the >=256 key
  2917. if (isset($extra)) {
  2918. $size = ">=$objects";
  2919. $objects = $extra;
  2920. }
  2921. $stats[$size] = $objects;
  2922. }
  2923. return $stats;
  2924. }
  2925. }
  2926. class Info_v24 extends Info {
  2927. public function parseResponse($data) {
  2928. $info = array();
  2929. $current = null;
  2930. $infoLines = explode("\r\n", $data, -1);
  2931. foreach ($infoLines as $row) {
  2932. if ($row === '') {
  2933. continue;
  2934. }
  2935. if (preg_match('/^# (\w+)$/', $row, $matches)) {
  2936. $info[$matches[1]] = array();
  2937. $current = &$info[$matches[1]];
  2938. continue;
  2939. }
  2940. list($k, $v) = explode(':', $row);
  2941. if (!preg_match('/^db\d+$/', $k)) {
  2942. if ($k === 'allocation_stats') {
  2943. $current[$k] = $this->parseAllocationStats($v);
  2944. continue;
  2945. }
  2946. $current[$k] = $v;
  2947. }
  2948. else {
  2949. $current[$k] = $this->parseDatabaseStats($v);
  2950. }
  2951. }
  2952. return $info;
  2953. }
  2954. }
  2955. class SlaveOf extends \Predis\MultiBulkCommand {
  2956. public function canBeHashed() { return false; }
  2957. public function getCommandId() { return 'SLAVEOF'; }
  2958. public function filterArguments(Array $arguments) {
  2959. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2960. return array('NO', 'ONE');
  2961. }
  2962. return $arguments;
  2963. }
  2964. }
  2965. class Config extends \Predis\MultiBulkCommand {
  2966. public function canBeHashed() { return false; }
  2967. public function getCommandId() { return 'CONFIG'; }
  2968. }
  2969. ?>