Predis.php 103 KB

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