Predis.php 104 KB

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