Predis.php 104 KB

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