Predis.php 103 KB

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