Predis.php 104 KB

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