Predis.php 104 KB

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