Predis.php 104 KB

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