Predis.php 104 KB

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