Predis.php 104 KB

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