Predis.php 104 KB

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