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