Predis.php 103 KB

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