Predis.php 104 KB

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