Predis.php 104 KB

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