Predis.php 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141
  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. const DEFAULT_SCHEME = 'tcp';
  735. const DEFAULT_HOST = '127.0.0.1';
  736. const DEFAULT_PORT = 6379;
  737. const DEFAULT_TIMEOUT = 5;
  738. private $_parameters;
  739. public function __construct($parameters = null) {
  740. $parameters = $parameters ?: array();
  741. $this->_parameters = is_array($parameters)
  742. ? self::filterConnectionParams($parameters)
  743. : self::parseURI($parameters);
  744. }
  745. private static function paramsExtractor($params, $kv) {
  746. @list($k, $v) = explode('=', $kv);
  747. $params[$k] = $v;
  748. return $params;
  749. }
  750. private static function parseURI($uri) {
  751. if (stripos($uri, 'unix') === 0) {
  752. // Hack to support URIs for UNIX sockets with minimal effort
  753. $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
  754. }
  755. $parsed = @parse_url($uri);
  756. if ($parsed == false || $parsed['host'] == null) {
  757. throw new ClientException("Invalid URI: $uri");
  758. }
  759. if (array_key_exists('query', $parsed)) {
  760. $query = explode('&', $parsed['query']);
  761. $parsed = array_reduce($query, 'self::paramsExtractor', $parsed);
  762. }
  763. return self::filterConnectionParams($parsed);
  764. }
  765. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  766. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  767. }
  768. private static function filterConnectionParams($parameters) {
  769. return array(
  770. 'scheme' => self::getParamOrDefault($parameters, 'scheme', self::DEFAULT_SCHEME),
  771. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  772. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  773. 'path' => self::getParamOrDefault($parameters, 'path'),
  774. 'database' => self::getParamOrDefault($parameters, 'database'),
  775. 'password' => self::getParamOrDefault($parameters, 'password'),
  776. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  777. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  778. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  779. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  780. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  781. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  782. );
  783. }
  784. public function __get($parameter) {
  785. return $this->_parameters[$parameter];
  786. }
  787. public function __isset($parameter) {
  788. return isset($this->_parameters[$parameter]);
  789. }
  790. }
  791. class ClientOptions {
  792. private static $_optionsHandlers;
  793. private $_options;
  794. public function __construct($options = null) {
  795. self::initializeOptionsHandlers();
  796. $this->initializeOptions($options ?: array());
  797. }
  798. private static function initializeOptionsHandlers() {
  799. if (!isset(self::$_optionsHandlers)) {
  800. self::$_optionsHandlers = self::getOptionsHandlers();
  801. }
  802. }
  803. private static function getOptionsHandlers() {
  804. return array(
  805. 'profile' => new ClientOptionsProfile(),
  806. 'key_distribution' => new ClientOptionsKeyDistribution(),
  807. 'iterable_multibulk' => new ClientOptionsIterableMultiBulk(),
  808. 'throw_on_error' => new ClientOptionsThrowOnError(),
  809. );
  810. }
  811. private function initializeOptions($options) {
  812. foreach ($options as $option => $value) {
  813. if (isset(self::$_optionsHandlers[$option])) {
  814. $handler = self::$_optionsHandlers[$option];
  815. $this->_options[$option] = $handler->validate($option, $value);
  816. }
  817. }
  818. }
  819. public function __get($option) {
  820. if (!isset($this->_options[$option])) {
  821. $defaultValue = self::$_optionsHandlers[$option]->getDefault();
  822. $this->_options[$option] = $defaultValue;
  823. }
  824. return $this->_options[$option];
  825. }
  826. public function __isset($option) {
  827. return isset(self::$_optionsHandlers[$option]);
  828. }
  829. }
  830. class Utils {
  831. public static function isCluster(IConnection $connection) {
  832. return $connection instanceof IConnectionCluster;
  833. }
  834. public static function onCommunicationException(CommunicationException $exception) {
  835. if ($exception->shouldResetConnection()) {
  836. $connection = $exception->getConnection();
  837. if ($connection->isConnected()) {
  838. $connection->disconnect();
  839. }
  840. }
  841. throw $exception;
  842. }
  843. public static function filterArrayArguments(Array $arguments) {
  844. if (count($arguments) === 1 && is_array($arguments[0])) {
  845. return $arguments[0];
  846. }
  847. return $arguments;
  848. }
  849. }
  850. /* -------------------------------------------------------------------------- */
  851. interface IClientOptionsHandler {
  852. public function validate($option, $value);
  853. public function getDefault();
  854. }
  855. class ClientOptionsProfile implements IClientOptionsHandler {
  856. public function validate($option, $value) {
  857. if ($value instanceof ServerProfile) {
  858. return $value;
  859. }
  860. if (is_string($value)) {
  861. return ServerProfile::get($value);
  862. }
  863. throw new \InvalidArgumentException("Invalid value for option $option");
  864. }
  865. public function getDefault() {
  866. return ServerProfile::getDefault();
  867. }
  868. }
  869. class ClientOptionsKeyDistribution implements IClientOptionsHandler {
  870. public function validate($option, $value) {
  871. if ($value instanceof IDistributionStrategy) {
  872. return $value;
  873. }
  874. if (is_string($value)) {
  875. $valueReflection = new \ReflectionClass($value);
  876. if ($valueReflection->isSubclassOf('\Predis\Distribution\IDistributionStrategy')) {
  877. return new $value;
  878. }
  879. }
  880. throw new \InvalidArgumentException("Invalid value for option $option");
  881. }
  882. public function getDefault() {
  883. return new Distribution\HashRing();
  884. }
  885. }
  886. class ClientOptionsIterableMultiBulk implements IClientOptionsHandler {
  887. public function validate($option, $value) {
  888. return (bool) $value;
  889. }
  890. public function getDefault() {
  891. return false;
  892. }
  893. }
  894. class ClientOptionsThrowOnError implements IClientOptionsHandler {
  895. public function validate($option, $value) {
  896. return (bool) $value;
  897. }
  898. public function getDefault() {
  899. return true;
  900. }
  901. }
  902. /* -------------------------------------------------------------------------- */
  903. namespace Predis\Network;
  904. use Predis\ICommand;
  905. use Predis\ConnectionParameters;
  906. use Predis\Protocols\IRedisProtocol;
  907. use Predis\Protocols\TextProtocol;
  908. use Predis\Distribution\IDistributionStrategy;
  909. interface IConnection {
  910. public function connect();
  911. public function disconnect();
  912. public function isConnected();
  913. public function writeCommand(ICommand $command);
  914. public function readResponse(ICommand $command);
  915. public function executeCommand(ICommand $command);
  916. }
  917. interface IConnectionSingle extends IConnection {
  918. public function getParameters();
  919. public function getProtocol();
  920. public function __toString();
  921. public function writeBytes($buffer);
  922. public function readBytes($length);
  923. public function readLine();
  924. public function pushInitCommand(ICommand $command);
  925. }
  926. interface IConnectionCluster extends IConnection {
  927. public function getConnection(ICommand $command);
  928. public function getConnectionById($connectionId);
  929. }
  930. abstract class ConnectionBase implements IConnectionSingle {
  931. protected $_params, $_socket, $_initCmds, $_protocol;
  932. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol) {
  933. $this->_initCmds = array();
  934. $this->_params = $parameters;
  935. $this->_protocol = $protocol;
  936. }
  937. public function __destruct() {
  938. $this->disconnect();
  939. }
  940. public function isConnected() {
  941. return is_resource($this->_socket);
  942. }
  943. protected abstract function createResource();
  944. public function connect() {
  945. if ($this->isConnected()) {
  946. throw new ClientException('Connection already estabilished');
  947. }
  948. $this->createResource();
  949. }
  950. public function disconnect() {
  951. if ($this->isConnected()) {
  952. fclose($this->_socket);
  953. }
  954. }
  955. public function pushInitCommand(ICommand $command){
  956. $this->_initCmds[] = $command;
  957. }
  958. public function executeCommand(ICommand $command) {
  959. $this->writeCommand($command);
  960. if ($command->closesConnection()) {
  961. return $this->disconnect();
  962. }
  963. return $this->readResponse($command);
  964. }
  965. protected function onCommunicationException($message, $code = null) {
  966. Utils::onCommunicationException(
  967. new CommunicationException($this, $message, $code)
  968. );
  969. }
  970. public function getResource() {
  971. if (!$this->isConnected()) {
  972. $this->connect();
  973. }
  974. return $this->_socket;
  975. }
  976. public function getParameters() {
  977. return $this->_params;
  978. }
  979. public function getProtocol() {
  980. return $this->_protocol;
  981. }
  982. public function __toString() {
  983. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  984. }
  985. }
  986. class TcpConnection extends ConnectionBase implements IConnectionSingle {
  987. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  988. parent::__construct($this->checkParameters($parameters), $protocol ?: new TextProtocol());
  989. }
  990. public function __destruct() {
  991. if (!$this->_params->connection_persistent) {
  992. $this->disconnect();
  993. }
  994. }
  995. protected function checkParameters(ConnectionParameters $parameters) {
  996. if ($parameters->scheme != 'tcp' && $parameters->scheme != 'redis') {
  997. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  998. }
  999. return $parameters;
  1000. }
  1001. protected function createResource() {
  1002. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  1003. $connectFlags = STREAM_CLIENT_CONNECT;
  1004. if ($this->_params->connection_async) {
  1005. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  1006. }
  1007. if ($this->_params->connection_persistent) {
  1008. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1009. }
  1010. $this->_socket = @stream_socket_client(
  1011. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1012. );
  1013. if (!$this->_socket) {
  1014. $this->onCommunicationException(trim($errstr), $errno);
  1015. }
  1016. if (isset($this->_params->read_write_timeout)) {
  1017. $timeoutSeconds = floor($this->_params->read_write_timeout);
  1018. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  1019. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  1020. }
  1021. }
  1022. private function sendInitializationCommands() {
  1023. foreach ($this->_initCmds as $command) {
  1024. $this->writeCommand($command);
  1025. }
  1026. foreach ($this->_initCmds as $command) {
  1027. $this->readResponse($command);
  1028. }
  1029. }
  1030. public function connect() {
  1031. parent::connect();
  1032. if (count($this->_initCmds) > 0){
  1033. $this->sendInitializationCommands();
  1034. }
  1035. }
  1036. public function writeCommand(ICommand $command) {
  1037. $this->_protocol->write($this, $command);
  1038. }
  1039. public function readResponse(ICommand $command) {
  1040. $response = $this->_protocol->read($this);
  1041. $skipparse = isset($response->queued) || isset($response->error);
  1042. return $skipparse ? $response : $command->parseResponse($response);
  1043. }
  1044. public function rawCommand($buffer) {
  1045. $this->writeBytes($buffer);
  1046. return $this->_protocol->read($this);
  1047. }
  1048. public function writeBytes($value) {
  1049. $socket = $this->getResource();
  1050. while (($length = strlen($value)) > 0) {
  1051. $written = fwrite($socket, $value);
  1052. if ($length === $written) {
  1053. return true;
  1054. }
  1055. if ($written === false || $written === 0) {
  1056. $this->onCommunicationException('Error while writing bytes to the server');
  1057. }
  1058. $value = substr($value, $written);
  1059. }
  1060. return true;
  1061. }
  1062. public function readBytes($length) {
  1063. if ($length <= 0) {
  1064. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  1065. }
  1066. $socket = $this->getResource();
  1067. $value = '';
  1068. do {
  1069. $chunk = fread($socket, $length);
  1070. if ($chunk === false || $chunk === '') {
  1071. $this->onCommunicationException('Error while reading bytes from the server');
  1072. }
  1073. $value .= $chunk;
  1074. }
  1075. while (($length -= strlen($chunk)) > 0);
  1076. return $value;
  1077. }
  1078. public function readLine() {
  1079. $socket = $this->getResource();
  1080. $value = '';
  1081. do {
  1082. $chunk = fgets($socket);
  1083. if ($chunk === false || $chunk === '') {
  1084. $this->onCommunicationException('Error while reading line from the server');
  1085. }
  1086. $value .= $chunk;
  1087. }
  1088. while (substr($value, -2) !== TextProtocol::NEWLINE);
  1089. return substr($value, 0, -2);
  1090. }
  1091. }
  1092. class UnixDomainSocketConnection extends TcpConnection {
  1093. public function __construct(ConnectionParameters $parameters, IRedisProtocol $protocol = null) {
  1094. parent::__construct($this->checkParameters($parameters), $protocol);
  1095. }
  1096. protected function checkParameters(ConnectionParameters $parameters) {
  1097. if ($parameters->scheme != 'unix') {
  1098. throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
  1099. }
  1100. if (!file_exists($parameters->path)) {
  1101. throw new \InvalidArgumentException("Could not find {$parameters->path}");
  1102. }
  1103. return $parameters;
  1104. }
  1105. protected function createResource() {
  1106. $uri = sprintf('unix:///%s', $this->_params->path);
  1107. $connectFlags = STREAM_CLIENT_CONNECT;
  1108. if ($this->_params->connection_persistent) {
  1109. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  1110. }
  1111. $this->_socket = @stream_socket_client(
  1112. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  1113. );
  1114. if (!$this->_socket) {
  1115. $this->onCommunicationException(trim($errstr), $errno);
  1116. }
  1117. }
  1118. }
  1119. class ConnectionCluster implements IConnectionCluster, \IteratorAggregate {
  1120. private $_pool, $_distributor;
  1121. public function __construct(IDistributionStrategy $distributor = null) {
  1122. $this->_pool = array();
  1123. $this->_distributor = $distributor ?: new Distribution\HashRing();
  1124. }
  1125. public function isConnected() {
  1126. foreach ($this->_pool as $connection) {
  1127. if ($connection->isConnected()) {
  1128. return true;
  1129. }
  1130. }
  1131. return false;
  1132. }
  1133. public function connect() {
  1134. foreach ($this->_pool as $connection) {
  1135. $connection->connect();
  1136. }
  1137. }
  1138. public function disconnect() {
  1139. foreach ($this->_pool as $connection) {
  1140. $connection->disconnect();
  1141. }
  1142. }
  1143. public function add(IConnectionSingle $connection) {
  1144. $parameters = $connection->getParameters();
  1145. if (isset($parameters->alias)) {
  1146. $this->_pool[$parameters->alias] = $connection;
  1147. }
  1148. else {
  1149. $this->_pool[] = $connection;
  1150. }
  1151. $this->_distributor->add($connection, $parameters->weight);
  1152. }
  1153. public function getConnection(ICommand $command) {
  1154. if ($command->canBeHashed() === false) {
  1155. throw new ClientException(
  1156. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getCommandId())
  1157. );
  1158. }
  1159. return $this->_distributor->get($command->getHash($this->_distributor));
  1160. }
  1161. public function getConnectionById($id = null) {
  1162. $alias = $id ?: 0;
  1163. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  1164. }
  1165. public function getIterator() {
  1166. return new \ArrayIterator($this->_pool);
  1167. }
  1168. public function writeCommand(ICommand $command) {
  1169. $this->getConnection($command)->writeCommand($command);
  1170. }
  1171. public function readResponse(ICommand $command) {
  1172. return $this->getConnection($command)->readResponse($command);
  1173. }
  1174. public function executeCommand(ICommand $command) {
  1175. $connection = $this->getConnection($command);
  1176. $connection->writeCommand($command);
  1177. return $connection->readResponse($command);
  1178. }
  1179. }
  1180. /* -------------------------------------------------------------------------- */
  1181. namespace Predis\Protocols;
  1182. use Predis\ICommand;
  1183. use Predis\Iterators;
  1184. use Predis\MalformedServerResponse;
  1185. use Predis\Network\IConnectionSingle;
  1186. interface IRedisProtocol {
  1187. public function setSerializer(ICommandSerializer $serializer);
  1188. public function getSerializer();
  1189. public function setReader(IResponseReader $reader);
  1190. public function getReader();
  1191. }
  1192. interface ICommandSerializer {
  1193. public function serialize(ICommand $command);
  1194. }
  1195. interface IResponseReader {
  1196. public function setHandler($prefix, IResponseHandler $handler);
  1197. public function getHandler($prefix);
  1198. }
  1199. interface IResponseHandler {
  1200. function handle(IConnectionSingle $connection, $payload);
  1201. }
  1202. class TextProtocol implements IRedisProtocol {
  1203. const NEWLINE = "\r\n";
  1204. const OK = 'OK';
  1205. const ERROR = 'ERR';
  1206. const QUEUED = 'QUEUED';
  1207. const NULL = 'nil';
  1208. const PREFIX_STATUS = '+';
  1209. const PREFIX_ERROR = '-';
  1210. const PREFIX_INTEGER = ':';
  1211. const PREFIX_BULK = '$';
  1212. const PREFIX_MULTI_BULK = '*';
  1213. private $_serializer, $_reader;
  1214. public function __construct(Array $options = array()) {
  1215. $this->setSerializer(new TextCommandSerializer());
  1216. $this->setReader(new TextResponseReader());
  1217. $this->initializeOptions($options);
  1218. }
  1219. private function getDefaultOptions() {
  1220. return array(
  1221. 'iterable_multibulk' => false,
  1222. 'throw_on_error' => false,
  1223. );
  1224. }
  1225. private function initializeOptions(Array $options) {
  1226. $options = array_merge($this->getDefaultOptions(), $options);
  1227. foreach ($options as $k => $v) {
  1228. $this->setOption($k, $v);
  1229. }
  1230. }
  1231. public function setOption($option, $value) {
  1232. switch ($option) {
  1233. case 'iterable_multibulk':
  1234. $handler = $value ? new ResponseMultiBulkStreamHandler() : new ResponseMultiBulkHandler();
  1235. $this->_reader->setHandler(self::PREFIX_MULTI_BULK, $handler);
  1236. break;
  1237. case 'throw_on_error':
  1238. $handler = $value ? new ResponseErrorHandler() : new ResponseErrorSilentHandler();
  1239. $this->_reader->setHandler(self::PREFIX_ERROR, $handler);
  1240. break;
  1241. default:
  1242. throw new \InvalidArgumentException(
  1243. "The option $option is not supported by the current protocol"
  1244. );
  1245. }
  1246. }
  1247. public function serialize(ICommand $command) {
  1248. return $this->_serializer->serialize($command);
  1249. }
  1250. public function write(IConnectionSingle $connection, ICommand $command) {
  1251. $connection->writeBytes($this->_serializer->serialize($command));
  1252. }
  1253. public function read(IConnectionSingle $connection) {
  1254. return $this->_reader->read($connection);
  1255. }
  1256. public function setSerializer(ICommandSerializer $serializer) {
  1257. $this->_serializer = $serializer;
  1258. }
  1259. public function getSerializer() {
  1260. return $this->_serializer;
  1261. }
  1262. public function setReader(IResponseReader $reader) {
  1263. $this->_reader = $reader;
  1264. }
  1265. public function getReader() {
  1266. return $this->_reader;
  1267. }
  1268. }
  1269. class TextCommandSerializer implements ICommandSerializer {
  1270. public function serialize(ICommand $command) {
  1271. $commandId = $command->getCommandId();
  1272. $arguments = $command->getArguments();
  1273. $newline = TextProtocol::NEWLINE;
  1274. $cmdlen = strlen($commandId);
  1275. $reqlen = count($arguments) + 1;
  1276. $buffer = "*{$reqlen}{$newline}\${$cmdlen}{$newline}{$commandId}{$newline}";
  1277. for ($i = 0; $i < $reqlen - 1; $i++) {
  1278. $argument = $arguments[$i];
  1279. $arglen = strlen($argument);
  1280. $buffer .= "\${$arglen}{$newline}{$argument}{$newline}";
  1281. }
  1282. return $buffer;
  1283. }
  1284. }
  1285. class TextResponseReader implements IResponseReader {
  1286. private $_prefixHandlers;
  1287. public function __construct() {
  1288. $this->_prefixHandlers = $this->getDefaultHandlers();
  1289. }
  1290. private function getDefaultHandlers() {
  1291. return array(
  1292. TextProtocol::PREFIX_STATUS => new ResponseStatusHandler(),
  1293. TextProtocol::PREFIX_ERROR => new ResponseErrorHandler(),
  1294. TextProtocol::PREFIX_INTEGER => new ResponseIntegerHandler(),
  1295. TextProtocol::PREFIX_BULK => new ResponseBulkHandler(),
  1296. TextProtocol::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  1297. );
  1298. }
  1299. public function setHandler($prefix, IResponseHandler $handler) {
  1300. $this->_prefixHandlers[$prefix] = $handler;
  1301. }
  1302. public function getHandler($prefix) {
  1303. if (isset($this->_prefixHandlers[$prefix])) {
  1304. return $this->_prefixHandlers[$prefix];
  1305. }
  1306. }
  1307. public function read(IConnectionSingle $connection) {
  1308. $header = $connection->readLine();
  1309. if ($header === '') {
  1310. $this->throwMalformedResponse('Unexpected empty header');
  1311. }
  1312. $prefix = $header[0];
  1313. if (!isset($this->_prefixHandlers[$prefix])) {
  1314. $this->throwMalformedResponse("Unknown prefix '$prefix'");
  1315. }
  1316. $handler = $this->_prefixHandlers[$prefix];
  1317. return $handler->handle($connection, substr($header, 1));
  1318. }
  1319. private function throwMalformedResponse($message) {
  1320. Utils::onCommunicationException(new MalformedServerResponse(
  1321. $connection, $message
  1322. ));
  1323. }
  1324. }
  1325. class ResponseStatusHandler implements IResponseHandler {
  1326. public function handle(IConnectionSingle $connection, $status) {
  1327. if ($status === TextProtocol::OK) {
  1328. return true;
  1329. }
  1330. if ($status === TextProtocol::QUEUED) {
  1331. return new \Predis\ResponseQueued();
  1332. }
  1333. return $status;
  1334. }
  1335. }
  1336. class ResponseErrorHandler implements IResponseHandler {
  1337. public function handle(IConnectionSingle $connection, $errorMessage) {
  1338. throw new \Predis\ServerException(substr($errorMessage, 4));
  1339. }
  1340. }
  1341. class ResponseErrorSilentHandler implements IResponseHandler {
  1342. public function handle(IConnectionSingle $connection, $errorMessage) {
  1343. return new \Predis\ResponseError(substr($errorMessage, 4));
  1344. }
  1345. }
  1346. class ResponseBulkHandler implements IResponseHandler {
  1347. public function handle(IConnectionSingle $connection, $length) {
  1348. if (!is_numeric($length)) {
  1349. Utils::onCommunicationException(new MalformedServerResponse(
  1350. $connection, "Cannot parse '$length' as data length"
  1351. ));
  1352. }
  1353. $length = (int) $length;
  1354. if ($length >= 0) {
  1355. $value = $length > 0 ? $connection->readBytes($length) : '';
  1356. if ($connection->readBytes(2) !== TextProtocol::NEWLINE) {
  1357. Utils::onCommunicationException(new MalformedServerResponse(
  1358. $connection, 'Did not receive a new-line at the end of a bulk response'
  1359. ));
  1360. }
  1361. return $value;
  1362. }
  1363. if ($length == -1) {
  1364. return null;
  1365. }
  1366. }
  1367. }
  1368. class ResponseMultiBulkHandler implements IResponseHandler {
  1369. public function handle(IConnectionSingle $connection, $length) {
  1370. if (!is_numeric($length)) {
  1371. Utils::onCommunicationException(new MalformedServerResponse(
  1372. $connection, "Cannot parse '$length' as data length"
  1373. ));
  1374. }
  1375. $length = (int) $length;
  1376. if ($length === -1) {
  1377. return null;
  1378. }
  1379. $list = array();
  1380. if ($length > 0) {
  1381. $handlersCache = array();
  1382. $reader = $connection->getProtocol()->getReader();
  1383. for ($i = 0; $i < $length; $i++) {
  1384. $header = $connection->readLine();
  1385. $prefix = $header[0];
  1386. if (isset($handlersCache[$prefix])) {
  1387. $handler = $handlersCache[$prefix];
  1388. }
  1389. else {
  1390. $handler = $reader->getHandler($prefix);
  1391. $handlersCache[$prefix] = $handler;
  1392. }
  1393. $list[$i] = $handler->handle($connection, substr($header, 1));
  1394. }
  1395. }
  1396. return $list;
  1397. }
  1398. }
  1399. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  1400. public function handle(IConnectionSingle $connection, $length) {
  1401. if (!is_numeric($length)) {
  1402. Utils::onCommunicationException(new MalformedServerResponse(
  1403. $connection, "Cannot parse '$length' as data length"
  1404. ));
  1405. }
  1406. return new Iterators\MultiBulkResponseSimple($connection, (int) $length);
  1407. }
  1408. }
  1409. class ResponseIntegerHandler implements IResponseHandler {
  1410. public function handle(IConnectionSingle $connection, $number) {
  1411. if (is_numeric($number)) {
  1412. return (int) $number;
  1413. }
  1414. else {
  1415. if ($number !== TextProtocol::NULL) {
  1416. Utils::onCommunicationException(new MalformedServerResponse(
  1417. $connection, "Cannot parse '$number' as numeric response"
  1418. ));
  1419. }
  1420. return null;
  1421. }
  1422. }
  1423. }
  1424. /* -------------------------------------------------------------------------- */
  1425. namespace Predis\Profiles;
  1426. use Predis\ClientException;
  1427. abstract class ServerProfile {
  1428. private static $_profiles;
  1429. private $_registeredCommands;
  1430. public function __construct() {
  1431. $this->_registeredCommands = $this->getSupportedCommands();
  1432. }
  1433. public abstract function getVersion();
  1434. protected abstract function getSupportedCommands();
  1435. public static function getDefault() {
  1436. return self::get('default');
  1437. }
  1438. public static function getDevelopment() {
  1439. return self::get('dev');
  1440. }
  1441. private static function getDefaultProfiles() {
  1442. return array(
  1443. '1.2' => '\Predis\Profiles\Server_v1_2',
  1444. '2.0' => '\Predis\Profiles\Server_v2_0',
  1445. 'default' => '\Predis\Profiles\Server_v2_0',
  1446. 'dev' => '\Predis\Profiles\Server_vNext',
  1447. );
  1448. }
  1449. public static function registerProfile($profileClass, $aliases) {
  1450. if (!isset(self::$_profiles)) {
  1451. self::$_profiles = self::getDefaultProfiles();
  1452. }
  1453. $profileReflection = new \ReflectionClass($profileClass);
  1454. if (!$profileReflection->isSubclassOf('\Predis\Profiles\ServerProfile')) {
  1455. throw new ClientException(
  1456. "Cannot register '$profileClass' as it is not a valid profile class"
  1457. );
  1458. }
  1459. if (is_array($aliases)) {
  1460. foreach ($aliases as $alias) {
  1461. self::$_profiles[$alias] = $profileClass;
  1462. }
  1463. }
  1464. else {
  1465. self::$_profiles[$aliases] = $profileClass;
  1466. }
  1467. }
  1468. public static function get($version) {
  1469. if (!isset(self::$_profiles)) {
  1470. self::$_profiles = self::getDefaultProfiles();
  1471. }
  1472. if (!isset(self::$_profiles[$version])) {
  1473. throw new ClientException("Unknown server profile: $version");
  1474. }
  1475. $profile = self::$_profiles[$version];
  1476. return new $profile();
  1477. }
  1478. public function supportsCommands(Array $commands) {
  1479. foreach ($commands as $command) {
  1480. if ($this->supportsCommand($command) === false) {
  1481. return false;
  1482. }
  1483. }
  1484. return true;
  1485. }
  1486. public function supportsCommand($command) {
  1487. return isset($this->_registeredCommands[$command]);
  1488. }
  1489. public function createCommand($method, $arguments = array()) {
  1490. if (!isset($this->_registeredCommands[$method])) {
  1491. throw new ClientException("'$method' is not a registered Redis command");
  1492. }
  1493. $commandClass = $this->_registeredCommands[$method];
  1494. $command = new $commandClass();
  1495. $command->setArgumentsArray($arguments);
  1496. return $command;
  1497. }
  1498. public function registerCommands(Array $commands) {
  1499. foreach ($commands as $command => $aliases) {
  1500. $this->registerCommand($command, $aliases);
  1501. }
  1502. }
  1503. public function registerCommand($command, $aliases) {
  1504. $commandReflection = new \ReflectionClass($command);
  1505. if (!$commandReflection->isSubclassOf('\Predis\ICommand')) {
  1506. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1507. }
  1508. if (is_array($aliases)) {
  1509. foreach ($aliases as $alias) {
  1510. $this->_registeredCommands[$alias] = $command;
  1511. }
  1512. }
  1513. else {
  1514. $this->_registeredCommands[$aliases] = $command;
  1515. }
  1516. }
  1517. public function __toString() {
  1518. return $this->getVersion();
  1519. }
  1520. }
  1521. class Server_v1_2 extends ServerProfile {
  1522. public function getVersion() { return '1.2'; }
  1523. public function getSupportedCommands() {
  1524. return array(
  1525. /* miscellaneous commands */
  1526. 'ping' => '\Predis\Commands\Ping',
  1527. 'echo' => '\Predis\Commands\DoEcho',
  1528. 'auth' => '\Predis\Commands\Auth',
  1529. /* connection handling */
  1530. 'quit' => '\Predis\Commands\Quit',
  1531. /* commands operating on string values */
  1532. 'set' => '\Predis\Commands\Set',
  1533. 'setnx' => '\Predis\Commands\SetPreserve',
  1534. 'mset' => '\Predis\Commands\SetMultiple',
  1535. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1536. 'get' => '\Predis\Commands\Get',
  1537. 'mget' => '\Predis\Commands\GetMultiple',
  1538. 'getset' => '\Predis\Commands\GetSet',
  1539. 'incr' => '\Predis\Commands\Increment',
  1540. 'incrby' => '\Predis\Commands\IncrementBy',
  1541. 'decr' => '\Predis\Commands\Decrement',
  1542. 'decrby' => '\Predis\Commands\DecrementBy',
  1543. 'exists' => '\Predis\Commands\Exists',
  1544. 'del' => '\Predis\Commands\Delete',
  1545. 'type' => '\Predis\Commands\Type',
  1546. /* commands operating on the key space */
  1547. 'keys' => '\Predis\Commands\Keys_v1_2',
  1548. 'randomkey' => '\Predis\Commands\RandomKey',
  1549. 'rename' => '\Predis\Commands\Rename',
  1550. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1551. 'expire' => '\Predis\Commands\Expire',
  1552. 'expireat' => '\Predis\Commands\ExpireAt',
  1553. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1554. 'ttl' => '\Predis\Commands\TimeToLive',
  1555. /* commands operating on lists */
  1556. 'rpush' => '\Predis\Commands\ListPushTail',
  1557. 'lpush' => '\Predis\Commands\ListPushHead',
  1558. 'llen' => '\Predis\Commands\ListLength',
  1559. 'lrange' => '\Predis\Commands\ListRange',
  1560. 'ltrim' => '\Predis\Commands\ListTrim',
  1561. 'lindex' => '\Predis\Commands\ListIndex',
  1562. 'lset' => '\Predis\Commands\ListSet',
  1563. 'lrem' => '\Predis\Commands\ListRemove',
  1564. 'lpop' => '\Predis\Commands\ListPopFirst',
  1565. 'rpop' => '\Predis\Commands\ListPopLast',
  1566. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1567. /* commands operating on sets */
  1568. 'sadd' => '\Predis\Commands\SetAdd',
  1569. 'srem' => '\Predis\Commands\SetRemove',
  1570. 'spop' => '\Predis\Commands\SetPop',
  1571. 'smove' => '\Predis\Commands\SetMove',
  1572. 'scard' => '\Predis\Commands\SetCardinality',
  1573. 'sismember' => '\Predis\Commands\SetIsMember',
  1574. 'sinter' => '\Predis\Commands\SetIntersection',
  1575. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1576. 'sunion' => '\Predis\Commands\SetUnion',
  1577. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1578. 'sdiff' => '\Predis\Commands\SetDifference',
  1579. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1580. 'smembers' => '\Predis\Commands\SetMembers',
  1581. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1582. /* commands operating on sorted sets */
  1583. 'zadd' => '\Predis\Commands\ZSetAdd',
  1584. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1585. 'zrem' => '\Predis\Commands\ZSetRemove',
  1586. 'zrange' => '\Predis\Commands\ZSetRange',
  1587. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1588. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1589. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1590. 'zscore' => '\Predis\Commands\ZSetScore',
  1591. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1592. /* multiple databases handling commands */
  1593. 'select' => '\Predis\Commands\SelectDatabase',
  1594. 'move' => '\Predis\Commands\MoveKey',
  1595. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1596. 'flushall' => '\Predis\Commands\FlushAll',
  1597. /* sorting */
  1598. 'sort' => '\Predis\Commands\Sort',
  1599. /* remote server control commands */
  1600. 'info' => '\Predis\Commands\Info',
  1601. 'slaveof' => '\Predis\Commands\SlaveOf',
  1602. /* persistence control commands */
  1603. 'save' => '\Predis\Commands\Save',
  1604. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1605. 'lastsave' => '\Predis\Commands\LastSave',
  1606. 'shutdown' => '\Predis\Commands\Shutdown',
  1607. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1608. );
  1609. }
  1610. }
  1611. class Server_v2_0 extends Server_v1_2 {
  1612. public function getVersion() { return '2.0'; }
  1613. public function getSupportedCommands() {
  1614. return array_merge(parent::getSupportedCommands(), array(
  1615. /* transactions */
  1616. 'multi' => '\Predis\Commands\Multi',
  1617. 'exec' => '\Predis\Commands\Exec',
  1618. 'discard' => '\Predis\Commands\Discard',
  1619. /* commands operating on string values */
  1620. 'setex' => '\Predis\Commands\SetExpire',
  1621. 'append' => '\Predis\Commands\Append',
  1622. 'substr' => '\Predis\Commands\Substr',
  1623. /* commands operating on the key space */
  1624. 'keys' => '\Predis\Commands\Keys',
  1625. /* commands operating on lists */
  1626. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1627. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1628. /* commands operating on sorted sets */
  1629. 'zunionstore' => '\Predis\Commands\ZSetUnionStore',
  1630. 'zinterstore' => '\Predis\Commands\ZSetIntersectionStore',
  1631. 'zcount' => '\Predis\Commands\ZSetCount',
  1632. 'zrank' => '\Predis\Commands\ZSetRank',
  1633. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1634. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1635. /* commands operating on hashes */
  1636. 'hset' => '\Predis\Commands\HashSet',
  1637. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1638. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1639. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1640. 'hget' => '\Predis\Commands\HashGet',
  1641. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1642. 'hdel' => '\Predis\Commands\HashDelete',
  1643. 'hexists' => '\Predis\Commands\HashExists',
  1644. 'hlen' => '\Predis\Commands\HashLength',
  1645. 'hkeys' => '\Predis\Commands\HashKeys',
  1646. 'hvals' => '\Predis\Commands\HashValues',
  1647. 'hgetall' => '\Predis\Commands\HashGetAll',
  1648. /* publish - subscribe */
  1649. 'subscribe' => '\Predis\Commands\Subscribe',
  1650. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1651. 'psubscribe' => '\Predis\Commands\SubscribeByPattern',
  1652. 'punsubscribe' => '\Predis\Commands\UnsubscribeByPattern',
  1653. 'publish' => '\Predis\Commands\Publish',
  1654. /* remote server control commands */
  1655. 'config' => '\Predis\Commands\Config',
  1656. ));
  1657. }
  1658. }
  1659. class Server_vNext extends Server_v2_0 {
  1660. public function getVersion() { return '2.1'; }
  1661. public function getSupportedCommands() {
  1662. return array_merge(parent::getSupportedCommands(), array(
  1663. /* transactions */
  1664. 'watch' => '\Predis\Commands\Watch',
  1665. 'unwatch' => '\Predis\Commands\Unwatch',
  1666. /* commands operating on string values */
  1667. 'strlen' => '\Predis\Commands\Strlen',
  1668. 'setrange' => '\Predis\Commands\SetRange',
  1669. 'getrange' => '\Predis\Commands\GetRange',
  1670. 'setbit' => '\Predis\Commands\SetBit',
  1671. 'getbit' => '\Predis\Commands\GetBit',
  1672. /* commands operating on the key space */
  1673. 'persist' => '\Predis\Commands\Persist',
  1674. /* commands operating on lists */
  1675. 'rpushx' => '\Predis\Commands\ListPushTailX',
  1676. 'lpushx' => '\Predis\Commands\ListPushHeadX',
  1677. 'linsert' => '\Predis\Commands\ListInsert',
  1678. 'brpoplpush' => '\Predis\Commands\ListPopLastPushHeadBlocking',
  1679. /* commands operating on sorted sets */
  1680. 'zrevrangebyscore' => '\Predis\Commands\ZSetReverseRangeByScore',
  1681. ));
  1682. }
  1683. }
  1684. /* -------------------------------------------------------------------------- */
  1685. namespace Predis\Distribution;
  1686. interface IDistributionStrategy {
  1687. public function add($node, $weight = null);
  1688. public function remove($node);
  1689. public function get($key);
  1690. public function generateKey($value);
  1691. }
  1692. class EmptyRingException extends \Exception {
  1693. }
  1694. class HashRing implements IDistributionStrategy {
  1695. const DEFAULT_REPLICAS = 128;
  1696. const DEFAULT_WEIGHT = 100;
  1697. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1698. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1699. $this->_replicas = $replicas;
  1700. $this->_nodes = array();
  1701. }
  1702. public function add($node, $weight = null) {
  1703. // In case of collisions in the hashes of the nodes, the node added
  1704. // last wins, thus the order in which nodes are added is significant.
  1705. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  1706. $this->reset();
  1707. }
  1708. public function remove($node) {
  1709. // A node is removed by resetting the ring so that it's recreated from
  1710. // scratch, in order to reassign possible hashes with collisions to the
  1711. // right node according to the order in which they were added in the
  1712. // first place.
  1713. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1714. if ($this->_nodes[$i]['object'] === $node) {
  1715. array_splice($this->_nodes, $i, 1);
  1716. $this->reset();
  1717. break;
  1718. }
  1719. }
  1720. }
  1721. private function reset() {
  1722. unset($this->_ring);
  1723. unset($this->_ringKeys);
  1724. unset($this->_ringKeysCount);
  1725. }
  1726. private function isInitialized() {
  1727. return isset($this->_ringKeys);
  1728. }
  1729. private function computeTotalWeight() {
  1730. // TODO: array_reduce + lambda for PHP 5.3
  1731. $totalWeight = 0;
  1732. foreach ($this->_nodes as $node) {
  1733. $totalWeight += $node['weight'];
  1734. }
  1735. return $totalWeight;
  1736. }
  1737. private function initialize() {
  1738. if ($this->isInitialized()) {
  1739. return;
  1740. }
  1741. if (count($this->_nodes) === 0) {
  1742. throw new EmptyRingException('Cannot initialize empty hashring');
  1743. }
  1744. $this->_ring = array();
  1745. $totalWeight = $this->computeTotalWeight();
  1746. $nodesCount = count($this->_nodes);
  1747. foreach ($this->_nodes as $node) {
  1748. $weightRatio = $node['weight'] / $totalWeight;
  1749. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1750. }
  1751. ksort($this->_ring, SORT_NUMERIC);
  1752. $this->_ringKeys = array_keys($this->_ring);
  1753. $this->_ringKeysCount = count($this->_ringKeys);
  1754. }
  1755. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1756. $nodeObject = $node['object'];
  1757. $nodeHash = (string) $nodeObject;
  1758. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1759. for ($i = 0; $i < $replicas; $i++) {
  1760. $key = crc32("$nodeHash:$i");
  1761. $ring[$key] = $nodeObject;
  1762. }
  1763. }
  1764. public function generateKey($value) {
  1765. return crc32($value);
  1766. }
  1767. public function get($key) {
  1768. return $this->_ring[$this->getNodeKey($key)];
  1769. }
  1770. private function getNodeKey($key) {
  1771. $this->initialize();
  1772. $ringKeys = $this->_ringKeys;
  1773. $upper = $this->_ringKeysCount - 1;
  1774. $lower = 0;
  1775. while ($lower <= $upper) {
  1776. $index = ($lower + $upper) >> 1;
  1777. $item = $ringKeys[$index];
  1778. if ($item > $key) {
  1779. $upper = $index - 1;
  1780. }
  1781. else if ($item < $key) {
  1782. $lower = $index + 1;
  1783. }
  1784. else {
  1785. return $item;
  1786. }
  1787. }
  1788. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1789. }
  1790. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1791. // Binary search for the last item in _ringkeys with a value less or
  1792. // equal to the key. If no such item exists, return the last item.
  1793. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1794. }
  1795. }
  1796. class KetamaPureRing extends HashRing {
  1797. const DEFAULT_REPLICAS = 160;
  1798. public function __construct() {
  1799. parent::__construct($this::DEFAULT_REPLICAS);
  1800. }
  1801. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1802. $nodeObject = $node['object'];
  1803. $nodeHash = (string) $nodeObject;
  1804. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1805. for ($i = 0; $i < $replicas; $i++) {
  1806. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1807. foreach ($unpackedDigest as $key) {
  1808. $ring[$key] = $nodeObject;
  1809. }
  1810. }
  1811. }
  1812. public function generateKey($value) {
  1813. $hash = unpack('V', md5($value, true));
  1814. return $hash[1];
  1815. }
  1816. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1817. // Binary search for the first item in _ringkeys with a value greater
  1818. // or equal to the key. If no such item exists, return the first item.
  1819. return $lower < $ringKeysCount ? $lower : 0;
  1820. }
  1821. }
  1822. /* -------------------------------------------------------------------------- */
  1823. namespace Predis\Pipeline;
  1824. use Predis\Network\IConnection;
  1825. interface IPipelineExecutor {
  1826. public function execute(IConnection $connection, &$commands);
  1827. }
  1828. class StandardExecutor implements IPipelineExecutor {
  1829. public function execute(IConnection $connection, &$commands) {
  1830. $sizeofPipe = count($commands);
  1831. $values = array();
  1832. foreach ($commands as $command) {
  1833. $connection->writeCommand($command);
  1834. }
  1835. try {
  1836. for ($i = 0; $i < $sizeofPipe; $i++) {
  1837. $response = $connection->readResponse($commands[$i]);
  1838. $values[] = $response instanceof Iterator
  1839. ? iterator_to_array($response)
  1840. : $response;
  1841. unset($commands[$i]);
  1842. }
  1843. }
  1844. catch (\Predis\ServerException $exception) {
  1845. // Force disconnection to prevent protocol desynchronization.
  1846. $connection->disconnect();
  1847. throw $exception;
  1848. }
  1849. return $values;
  1850. }
  1851. }
  1852. class SafeExecutor implements IPipelineExecutor {
  1853. public function execute(IConnection $connection, &$commands) {
  1854. $sizeofPipe = count($commands);
  1855. $values = array();
  1856. foreach ($commands as $command) {
  1857. try {
  1858. $connection->writeCommand($command);
  1859. }
  1860. catch (\Predis\CommunicationException $exception) {
  1861. return array_fill(0, $sizeofPipe, $exception);
  1862. }
  1863. }
  1864. for ($i = 0; $i < $sizeofPipe; $i++) {
  1865. $command = $commands[$i];
  1866. unset($commands[$i]);
  1867. try {
  1868. $response = $connection->readResponse($command);
  1869. $values[] = ($response instanceof \Iterator
  1870. ? iterator_to_array($response)
  1871. : $response
  1872. );
  1873. }
  1874. catch (\Predis\ServerException $exception) {
  1875. $values[] = $exception->toResponseError();
  1876. }
  1877. catch (\Predis\CommunicationException $exception) {
  1878. $toAdd = count($commands) - count($values);
  1879. $values = array_merge($values, array_fill(0, $toAdd, $exception));
  1880. break;
  1881. }
  1882. }
  1883. return $values;
  1884. }
  1885. }
  1886. class SafeClusterExecutor implements IPipelineExecutor {
  1887. public function execute(IConnection $connection, &$commands) {
  1888. $connectionExceptions = array();
  1889. $sizeofPipe = count($commands);
  1890. $values = array();
  1891. foreach ($commands as $command) {
  1892. $cmdConnection = $connection->getConnection($command);
  1893. if (isset($connectionExceptions[spl_object_hash($cmdConnection)])) {
  1894. continue;
  1895. }
  1896. try {
  1897. $cmdConnection->writeCommand($command);
  1898. }
  1899. catch (\Predis\CommunicationException $exception) {
  1900. $connectionExceptions[spl_object_hash($cmdConnection)] = $exception;
  1901. }
  1902. }
  1903. for ($i = 0; $i < $sizeofPipe; $i++) {
  1904. $command = $commands[$i];
  1905. unset($commands[$i]);
  1906. $cmdConnection = $connection->getConnection($command);
  1907. $connectionObjectHash = spl_object_hash($cmdConnection);
  1908. if (isset($connectionExceptions[$connectionObjectHash])) {
  1909. $values[] = $connectionExceptions[$connectionObjectHash];
  1910. continue;
  1911. }
  1912. try {
  1913. $response = $cmdConnection->readResponse($command);
  1914. $values[] = ($response instanceof \Iterator
  1915. ? iterator_to_array($response)
  1916. : $response
  1917. );
  1918. }
  1919. catch (\Predis\ServerException $exception) {
  1920. $values[] = $exception->toResponseError();
  1921. }
  1922. catch (\Predis\CommunicationException $exception) {
  1923. $values[] = $exception;
  1924. $connectionExceptions[$connectionObjectHash] = $exception;
  1925. }
  1926. }
  1927. return $values;
  1928. }
  1929. }
  1930. /* -------------------------------------------------------------------------- */
  1931. namespace Predis\Iterators;
  1932. use Predis\CommunicationException;
  1933. use Predis\Network\IConnection;
  1934. use Predis\Network\IConnectionSingle;
  1935. abstract class MultiBulkResponse implements \Iterator, \Countable {
  1936. protected $_position, $_current, $_replySize;
  1937. public function rewind() {
  1938. // NOOP
  1939. }
  1940. public function current() {
  1941. return $this->_current;
  1942. }
  1943. public function key() {
  1944. return $this->_position;
  1945. }
  1946. public function next() {
  1947. if (++$this->_position < $this->_replySize) {
  1948. $this->_current = $this->getValue();
  1949. }
  1950. return $this->_position;
  1951. }
  1952. public function valid() {
  1953. return $this->_position < $this->_replySize;
  1954. }
  1955. public function count() {
  1956. // Use count if you want to get the size of the current multi-bulk
  1957. // response without using iterator_count (which actually consumes our
  1958. // iterator to calculate the size, and we cannot perform a rewind)
  1959. return $this->_replySize;
  1960. }
  1961. protected abstract function getValue();
  1962. }
  1963. class MultiBulkResponseSimple extends MultiBulkResponse {
  1964. private $_connection;
  1965. public function __construct(IConnectionSingle $connection, $size) {
  1966. $this->_connection = $connection;
  1967. $this->_protocol = $connection->getProtocol();
  1968. $this->_position = 0;
  1969. $this->_current = $size > 0 ? $this->getValue() : null;
  1970. $this->_replySize = $size;
  1971. }
  1972. public function __destruct() {
  1973. // When the iterator is garbage-collected (e.g. it goes out of the
  1974. // scope of a foreach) but it has not reached its end, we must sync
  1975. // the client with the queued elements that have not been read from
  1976. // the connection with the server.
  1977. $this->sync();
  1978. }
  1979. public function sync($drop = false) {
  1980. if ($drop == true) {
  1981. if ($this->valid()) {
  1982. $this->_position = $this->_replySize;
  1983. $this->_connection->disconnect();
  1984. }
  1985. }
  1986. else {
  1987. while ($this->valid()) {
  1988. $this->next();
  1989. }
  1990. }
  1991. }
  1992. protected function getValue() {
  1993. return $this->_protocol->read($this->_connection);
  1994. }
  1995. }
  1996. class MultiBulkResponseTuple extends MultiBulkResponse {
  1997. private $_iterator;
  1998. public function __construct(MultiBulkResponseSimple $iterator) {
  1999. $virtualSize = count($iterator) / 2;
  2000. $this->_iterator = $iterator;
  2001. $this->_position = 0;
  2002. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  2003. $this->_replySize = $virtualSize;
  2004. }
  2005. public function __destruct() {
  2006. $this->_iterator->sync();
  2007. }
  2008. protected function getValue() {
  2009. $k = $this->_iterator->current();
  2010. $this->_iterator->next();
  2011. $v = $this->_iterator->current();
  2012. $this->_iterator->next();
  2013. return array($k, $v);
  2014. }
  2015. }
  2016. /* -------------------------------------------------------------------------- */
  2017. namespace Predis\Commands;
  2018. use Predis\Utils;
  2019. use Predis\Command;
  2020. use Predis\Iterators\MultiBulkResponseTuple;
  2021. /* miscellaneous commands */
  2022. class Ping extends Command {
  2023. public function canBeHashed() { return false; }
  2024. public function getCommandId() { return 'PING'; }
  2025. public function parseResponse($data) {
  2026. return $data === 'PONG' ? true : false;
  2027. }
  2028. }
  2029. class DoEcho extends Command {
  2030. public function canBeHashed() { return false; }
  2031. public function getCommandId() { return 'ECHO'; }
  2032. }
  2033. class Auth extends Command {
  2034. public function canBeHashed() { return false; }
  2035. public function getCommandId() { return 'AUTH'; }
  2036. }
  2037. /* connection handling */
  2038. class Quit extends Command {
  2039. public function canBeHashed() { return false; }
  2040. public function getCommandId() { return 'QUIT'; }
  2041. public function closesConnection() { return true; }
  2042. }
  2043. /* commands operating on string values */
  2044. class Set extends Command {
  2045. public function getCommandId() { return 'SET'; }
  2046. }
  2047. class SetExpire extends Command {
  2048. public function getCommandId() { return 'SETEX'; }
  2049. }
  2050. class SetPreserve extends Command {
  2051. public function getCommandId() { return 'SETNX'; }
  2052. public function parseResponse($data) { return (bool) $data; }
  2053. }
  2054. class SetMultiple extends Command {
  2055. public function canBeHashed() { return false; }
  2056. public function getCommandId() { return 'MSET'; }
  2057. public function filterArguments(Array $arguments) {
  2058. if (count($arguments) === 1 && is_array($arguments[0])) {
  2059. $flattenedKVs = array();
  2060. $args = &$arguments[0];
  2061. foreach ($args as $k => $v) {
  2062. $flattenedKVs[] = $k;
  2063. $flattenedKVs[] = $v;
  2064. }
  2065. return $flattenedKVs;
  2066. }
  2067. return $arguments;
  2068. }
  2069. }
  2070. class SetMultiplePreserve extends SetMultiple {
  2071. public function canBeHashed() { return false; }
  2072. public function getCommandId() { return 'MSETNX'; }
  2073. public function parseResponse($data) { return (bool) $data; }
  2074. }
  2075. class Get extends Command {
  2076. public function getCommandId() { return 'GET'; }
  2077. }
  2078. class GetMultiple extends Command {
  2079. public function canBeHashed() { return false; }
  2080. public function getCommandId() { return 'MGET'; }
  2081. public function filterArguments(Array $arguments) {
  2082. return Utils::filterArrayArguments($arguments);
  2083. }
  2084. }
  2085. class GetSet extends Command {
  2086. public function getCommandId() { return 'GETSET'; }
  2087. }
  2088. class Increment extends Command {
  2089. public function getCommandId() { return 'INCR'; }
  2090. }
  2091. class IncrementBy extends Command {
  2092. public function getCommandId() { return 'INCRBY'; }
  2093. }
  2094. class Decrement extends Command {
  2095. public function getCommandId() { return 'DECR'; }
  2096. }
  2097. class DecrementBy extends Command {
  2098. public function getCommandId() { return 'DECRBY'; }
  2099. }
  2100. class Exists extends Command {
  2101. public function getCommandId() { return 'EXISTS'; }
  2102. public function parseResponse($data) { return (bool) $data; }
  2103. }
  2104. class Delete extends Command {
  2105. public function getCommandId() { return 'DEL'; }
  2106. public function filterArguments(Array $arguments) {
  2107. return Utils::filterArrayArguments($arguments);
  2108. }
  2109. }
  2110. class Type extends Command {
  2111. public function getCommandId() { return 'TYPE'; }
  2112. }
  2113. class Append extends Command {
  2114. public function getCommandId() { return 'APPEND'; }
  2115. }
  2116. class SetRange extends Command {
  2117. public function getCommandId() { return 'SETRANGE'; }
  2118. }
  2119. class GetRange extends Command {
  2120. public function getCommandId() { return 'GETRANGE'; }
  2121. }
  2122. class Substr extends Command {
  2123. public function getCommandId() { return 'SUBSTR'; }
  2124. }
  2125. class SetBit extends Command {
  2126. public function getCommandId() { return 'SETBIT'; }
  2127. }
  2128. class GetBit extends Command {
  2129. public function getCommandId() { return 'GETBIT'; }
  2130. }
  2131. class Strlen extends Command {
  2132. public function getCommandId() { return 'STRLEN'; }
  2133. }
  2134. /* commands operating on the key space */
  2135. class Keys extends Command {
  2136. public function canBeHashed() { return false; }
  2137. public function getCommandId() { return 'KEYS'; }
  2138. }
  2139. class Keys_v1_2 extends Keys {
  2140. public function parseResponse($data) {
  2141. return explode(' ', $data);
  2142. }
  2143. }
  2144. class RandomKey extends Command {
  2145. public function canBeHashed() { return false; }
  2146. public function getCommandId() { return 'RANDOMKEY'; }
  2147. public function parseResponse($data) { return $data !== '' ? $data : null; }
  2148. }
  2149. class Rename extends Command {
  2150. public function canBeHashed() { return false; }
  2151. public function getCommandId() { return 'RENAME'; }
  2152. }
  2153. class RenamePreserve extends Command {
  2154. public function canBeHashed() { return false; }
  2155. public function getCommandId() { return 'RENAMENX'; }
  2156. public function parseResponse($data) { return (bool) $data; }
  2157. }
  2158. class Expire extends Command {
  2159. public function getCommandId() { return 'EXPIRE'; }
  2160. public function parseResponse($data) { return (bool) $data; }
  2161. }
  2162. class ExpireAt extends Command {
  2163. public function getCommandId() { return 'EXPIREAT'; }
  2164. public function parseResponse($data) { return (bool) $data; }
  2165. }
  2166. class Persist extends Command {
  2167. public function getCommandId() { return 'PERSIST'; }
  2168. public function parseResponse($data) { return (bool) $data; }
  2169. }
  2170. class DatabaseSize extends Command {
  2171. public function canBeHashed() { return false; }
  2172. public function getCommandId() { return 'DBSIZE'; }
  2173. }
  2174. class TimeToLive extends Command {
  2175. public function getCommandId() { return 'TTL'; }
  2176. }
  2177. /* commands operating on lists */
  2178. class ListPushTail extends Command {
  2179. public function getCommandId() { return 'RPUSH'; }
  2180. }
  2181. class ListPushTailX extends Command {
  2182. public function getCommandId() { return 'RPUSHX'; }
  2183. }
  2184. class ListPushHead extends Command {
  2185. public function getCommandId() { return 'LPUSH'; }
  2186. }
  2187. class ListPushHeadX extends Command {
  2188. public function getCommandId() { return 'LPUSHX'; }
  2189. }
  2190. class ListLength extends Command {
  2191. public function getCommandId() { return 'LLEN'; }
  2192. }
  2193. class ListRange extends Command {
  2194. public function getCommandId() { return 'LRANGE'; }
  2195. }
  2196. class ListTrim extends Command {
  2197. public function getCommandId() { return 'LTRIM'; }
  2198. }
  2199. class ListIndex extends Command {
  2200. public function getCommandId() { return 'LINDEX'; }
  2201. }
  2202. class ListSet extends Command {
  2203. public function getCommandId() { return 'LSET'; }
  2204. }
  2205. class ListRemove extends Command {
  2206. public function getCommandId() { return 'LREM'; }
  2207. }
  2208. class ListPopLastPushHead extends Command {
  2209. public function getCommandId() { return 'RPOPLPUSH'; }
  2210. }
  2211. class ListPopLastPushHeadBlocking extends Command {
  2212. public function getCommandId() { return 'BRPOPLPUSH'; }
  2213. }
  2214. class ListPopFirst extends Command {
  2215. public function getCommandId() { return 'LPOP'; }
  2216. }
  2217. class ListPopLast extends Command {
  2218. public function getCommandId() { return 'RPOP'; }
  2219. }
  2220. class ListPopFirstBlocking extends Command {
  2221. public function getCommandId() { return 'BLPOP'; }
  2222. }
  2223. class ListPopLastBlocking extends Command {
  2224. public function getCommandId() { return 'BRPOP'; }
  2225. }
  2226. class ListInsert extends Command {
  2227. public function getCommandId() { return 'LINSERT'; }
  2228. }
  2229. /* commands operating on sets */
  2230. class SetAdd extends Command {
  2231. public function getCommandId() { return 'SADD'; }
  2232. public function parseResponse($data) { return (bool) $data; }
  2233. }
  2234. class SetRemove extends Command {
  2235. public function getCommandId() { return 'SREM'; }
  2236. public function parseResponse($data) { return (bool) $data; }
  2237. }
  2238. class SetPop extends Command {
  2239. public function getCommandId() { return 'SPOP'; }
  2240. }
  2241. class SetMove extends Command {
  2242. public function canBeHashed() { return false; }
  2243. public function getCommandId() { return 'SMOVE'; }
  2244. public function parseResponse($data) { return (bool) $data; }
  2245. }
  2246. class SetCardinality extends Command {
  2247. public function getCommandId() { return 'SCARD'; }
  2248. }
  2249. class SetIsMember extends Command {
  2250. public function getCommandId() { return 'SISMEMBER'; }
  2251. public function parseResponse($data) { return (bool) $data; }
  2252. }
  2253. class SetIntersection extends Command {
  2254. public function getCommandId() { return 'SINTER'; }
  2255. public function filterArguments(Array $arguments) {
  2256. return Utils::filterArrayArguments($arguments);
  2257. }
  2258. }
  2259. class SetIntersectionStore extends Command {
  2260. public function getCommandId() { return 'SINTERSTORE'; }
  2261. public function filterArguments(Array $arguments) {
  2262. return Utils::filterArrayArguments($arguments);
  2263. }
  2264. }
  2265. class SetUnion extends SetIntersection {
  2266. public function getCommandId() { return 'SUNION'; }
  2267. }
  2268. class SetUnionStore extends SetIntersectionStore {
  2269. public function getCommandId() { return 'SUNIONSTORE'; }
  2270. }
  2271. class SetDifference extends SetIntersection {
  2272. public function getCommandId() { return 'SDIFF'; }
  2273. }
  2274. class SetDifferenceStore extends SetIntersectionStore {
  2275. public function getCommandId() { return 'SDIFFSTORE'; }
  2276. }
  2277. class SetMembers extends Command {
  2278. public function getCommandId() { return 'SMEMBERS'; }
  2279. }
  2280. class SetRandomMember extends Command {
  2281. public function getCommandId() { return 'SRANDMEMBER'; }
  2282. }
  2283. /* commands operating on sorted sets */
  2284. class ZSetAdd extends Command {
  2285. public function getCommandId() { return 'ZADD'; }
  2286. public function parseResponse($data) { return (bool) $data; }
  2287. }
  2288. class ZSetIncrementBy extends Command {
  2289. public function getCommandId() { return 'ZINCRBY'; }
  2290. }
  2291. class ZSetRemove extends Command {
  2292. public function getCommandId() { return 'ZREM'; }
  2293. public function parseResponse($data) { return (bool) $data; }
  2294. }
  2295. class ZSetUnionStore extends Command {
  2296. public function getCommandId() { return 'ZUNIONSTORE'; }
  2297. public function filterArguments(Array $arguments) {
  2298. $options = array();
  2299. $argc = count($arguments);
  2300. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  2301. $options = $this->prepareOptions(array_pop($arguments));
  2302. }
  2303. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  2304. return array_merge($args, $options);
  2305. }
  2306. private function prepareOptions($options) {
  2307. $opts = array_change_key_case($options, CASE_UPPER);
  2308. $finalizedOpts = array();
  2309. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  2310. $finalizedOpts[] = 'WEIGHTS';
  2311. foreach ($opts['WEIGHTS'] as $weight) {
  2312. $finalizedOpts[] = $weight;
  2313. }
  2314. }
  2315. if (isset($opts['AGGREGATE'])) {
  2316. $finalizedOpts[] = 'AGGREGATE';
  2317. $finalizedOpts[] = $opts['AGGREGATE'];
  2318. }
  2319. return $finalizedOpts;
  2320. }
  2321. }
  2322. class ZSetIntersectionStore extends ZSetUnionStore {
  2323. public function getCommandId() { return 'ZINTERSTORE'; }
  2324. }
  2325. class ZSetRange extends Command {
  2326. private $_withScores = false;
  2327. public function getCommandId() { return 'ZRANGE'; }
  2328. public function filterArguments(Array $arguments) {
  2329. if (count($arguments) === 4) {
  2330. $lastType = gettype($arguments[3]);
  2331. if ($lastType === 'string' && strtolower($arguments[3]) === 'withscores') {
  2332. // Used for compatibility with older versions
  2333. $arguments[3] = array('WITHSCORES' => true);
  2334. $lastType = 'array';
  2335. }
  2336. if ($lastType === 'array') {
  2337. $options = $this->prepareOptions(array_pop($arguments));
  2338. return array_merge($arguments, $options);
  2339. }
  2340. }
  2341. return $arguments;
  2342. }
  2343. protected function prepareOptions($options) {
  2344. $opts = array_change_key_case($options, CASE_UPPER);
  2345. $finalizedOpts = array();
  2346. if (isset($opts['WITHSCORES'])) {
  2347. $finalizedOpts[] = 'WITHSCORES';
  2348. $this->_withScores = true;
  2349. }
  2350. return $finalizedOpts;
  2351. }
  2352. public function parseResponse($data) {
  2353. if ($this->_withScores) {
  2354. if ($data instanceof \Iterator) {
  2355. return new MultiBulkResponseTuple($data);
  2356. }
  2357. $result = array();
  2358. for ($i = 0; $i < count($data); $i++) {
  2359. $result[] = array($data[$i], $data[++$i]);
  2360. }
  2361. return $result;
  2362. }
  2363. return $data;
  2364. }
  2365. }
  2366. class ZSetReverseRange extends ZSetRange {
  2367. public function getCommandId() { return 'ZREVRANGE'; }
  2368. }
  2369. class ZSetRangeByScore extends ZSetRange {
  2370. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  2371. protected function prepareOptions($options) {
  2372. $opts = array_change_key_case($options, CASE_UPPER);
  2373. $finalizedOpts = array();
  2374. if (isset($opts['LIMIT']) && is_array($opts['LIMIT'])) {
  2375. $limit = array_change_key_case($opts['LIMIT'], CASE_UPPER);
  2376. $finalizedOpts[] = 'LIMIT';
  2377. $finalizedOpts[] = isset($limit['OFFSET']) ? $limit['OFFSET'] : $limit[0];
  2378. $finalizedOpts[] = isset($limit['COUNT']) ? $limit['COUNT'] : $limit[1];
  2379. }
  2380. return array_merge($finalizedOpts, parent::prepareOptions($options));
  2381. }
  2382. }
  2383. class ZSetReverseRangeByScore extends ZSetRangeByScore {
  2384. public function getCommandId() { return 'ZREVRANGEBYSCORE'; }
  2385. }
  2386. class ZSetCount extends Command {
  2387. public function getCommandId() { return 'ZCOUNT'; }
  2388. }
  2389. class ZSetCardinality extends Command {
  2390. public function getCommandId() { return 'ZCARD'; }
  2391. }
  2392. class ZSetScore extends Command {
  2393. public function getCommandId() { return 'ZSCORE'; }
  2394. }
  2395. class ZSetRemoveRangeByScore extends Command {
  2396. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  2397. }
  2398. class ZSetRank extends Command {
  2399. public function getCommandId() { return 'ZRANK'; }
  2400. }
  2401. class ZSetReverseRank extends Command {
  2402. public function getCommandId() { return 'ZREVRANK'; }
  2403. }
  2404. class ZSetRemoveRangeByRank extends Command {
  2405. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  2406. }
  2407. /* commands operating on hashes */
  2408. class HashSet extends Command {
  2409. public function getCommandId() { return 'HSET'; }
  2410. public function parseResponse($data) { return (bool) $data; }
  2411. }
  2412. class HashSetPreserve extends Command {
  2413. public function getCommandId() { return 'HSETNX'; }
  2414. public function parseResponse($data) { return (bool) $data; }
  2415. }
  2416. class HashSetMultiple extends Command {
  2417. public function getCommandId() { return 'HMSET'; }
  2418. public function filterArguments(Array $arguments) {
  2419. if (count($arguments) === 2 && is_array($arguments[1])) {
  2420. $flattenedKVs = array($arguments[0]);
  2421. $args = &$arguments[1];
  2422. foreach ($args as $k => $v) {
  2423. $flattenedKVs[] = $k;
  2424. $flattenedKVs[] = $v;
  2425. }
  2426. return $flattenedKVs;
  2427. }
  2428. return $arguments;
  2429. }
  2430. }
  2431. class HashIncrementBy extends Command {
  2432. public function getCommandId() { return 'HINCRBY'; }
  2433. }
  2434. class HashGet extends Command {
  2435. public function getCommandId() { return 'HGET'; }
  2436. }
  2437. class HashGetMultiple extends Command {
  2438. public function getCommandId() { return 'HMGET'; }
  2439. public function filterArguments(Array $arguments) {
  2440. if (count($arguments) === 2 && is_array($arguments[1])) {
  2441. $flattenedKVs = array($arguments[0]);
  2442. $args = &$arguments[1];
  2443. foreach ($args as $v) {
  2444. $flattenedKVs[] = $v;
  2445. }
  2446. return $flattenedKVs;
  2447. }
  2448. return $arguments;
  2449. }
  2450. }
  2451. class HashDelete extends Command {
  2452. public function getCommandId() { return 'HDEL'; }
  2453. public function parseResponse($data) { return (bool) $data; }
  2454. }
  2455. class HashExists extends Command {
  2456. public function getCommandId() { return 'HEXISTS'; }
  2457. public function parseResponse($data) { return (bool) $data; }
  2458. }
  2459. class HashLength extends Command {
  2460. public function getCommandId() { return 'HLEN'; }
  2461. }
  2462. class HashKeys extends Command {
  2463. public function getCommandId() { return 'HKEYS'; }
  2464. }
  2465. class HashValues extends Command {
  2466. public function getCommandId() { return 'HVALS'; }
  2467. }
  2468. class HashGetAll extends Command {
  2469. public function getCommandId() { return 'HGETALL'; }
  2470. public function parseResponse($data) {
  2471. if ($data instanceof \Iterator) {
  2472. return new MultiBulkResponseTuple($data);
  2473. }
  2474. $result = array();
  2475. for ($i = 0; $i < count($data); $i++) {
  2476. $result[$data[$i]] = $data[++$i];
  2477. }
  2478. return $result;
  2479. }
  2480. }
  2481. /* multiple databases handling commands */
  2482. class SelectDatabase extends Command {
  2483. public function canBeHashed() { return false; }
  2484. public function getCommandId() { return 'SELECT'; }
  2485. }
  2486. class MoveKey extends Command {
  2487. public function canBeHashed() { return false; }
  2488. public function getCommandId() { return 'MOVE'; }
  2489. public function parseResponse($data) { return (bool) $data; }
  2490. }
  2491. class FlushDatabase extends Command {
  2492. public function canBeHashed() { return false; }
  2493. public function getCommandId() { return 'FLUSHDB'; }
  2494. }
  2495. class FlushAll extends Command {
  2496. public function canBeHashed() { return false; }
  2497. public function getCommandId() { return 'FLUSHALL'; }
  2498. }
  2499. /* sorting */
  2500. class Sort extends Command {
  2501. public function getCommandId() { return 'SORT'; }
  2502. public function filterArguments(Array $arguments) {
  2503. if (count($arguments) === 1) {
  2504. return $arguments;
  2505. }
  2506. $query = array($arguments[0]);
  2507. $sortParams = array_change_key_case($arguments[1], CASE_UPPER);
  2508. if (isset($sortParams['BY'])) {
  2509. $query[] = 'BY';
  2510. $query[] = $sortParams['BY'];
  2511. }
  2512. if (isset($sortParams['GET'])) {
  2513. $getargs = $sortParams['GET'];
  2514. if (is_array($getargs)) {
  2515. foreach ($getargs as $getarg) {
  2516. $query[] = 'GET';
  2517. $query[] = $getarg;
  2518. }
  2519. }
  2520. else {
  2521. $query[] = 'GET';
  2522. $query[] = $getargs;
  2523. }
  2524. }
  2525. if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
  2526. && count($sortParams['LIMIT']) == 2) {
  2527. $query[] = 'LIMIT';
  2528. $query[] = $sortParams['LIMIT'][0];
  2529. $query[] = $sortParams['LIMIT'][1];
  2530. }
  2531. if (isset($sortParams['SORT'])) {
  2532. $query[] = strtoupper($sortParams['SORT']);
  2533. }
  2534. if (isset($sortParams['ALPHA']) && $sortParams['ALPHA'] == true) {
  2535. $query[] = 'ALPHA';
  2536. }
  2537. if (isset($sortParams['STORE'])) {
  2538. $query[] = 'STORE';
  2539. $query[] = $sortParams['STORE'];
  2540. }
  2541. return $query;
  2542. }
  2543. }
  2544. /* transactions */
  2545. class Multi extends Command {
  2546. public function canBeHashed() { return false; }
  2547. public function getCommandId() { return 'MULTI'; }
  2548. }
  2549. class Exec extends Command {
  2550. public function canBeHashed() { return false; }
  2551. public function getCommandId() { return 'EXEC'; }
  2552. }
  2553. class Discard extends Command {
  2554. public function canBeHashed() { return false; }
  2555. public function getCommandId() { return 'DISCARD'; }
  2556. }
  2557. class Watch extends Command {
  2558. public function canBeHashed() { return false; }
  2559. public function getCommandId() { return 'WATCH'; }
  2560. public function filterArguments(Array $arguments) {
  2561. if (isset($arguments[0]) && is_array($arguments[0])) {
  2562. return $arguments[0];
  2563. }
  2564. return $arguments;
  2565. }
  2566. public function parseResponse($data) { return (bool) $data; }
  2567. }
  2568. class Unwatch extends Command {
  2569. public function canBeHashed() { return false; }
  2570. public function getCommandId() { return 'UNWATCH'; }
  2571. public function parseResponse($data) { return (bool) $data; }
  2572. }
  2573. /* publish/subscribe */
  2574. class Subscribe extends Command {
  2575. public function canBeHashed() { return false; }
  2576. public function getCommandId() { return 'SUBSCRIBE'; }
  2577. }
  2578. class Unsubscribe extends Command {
  2579. public function canBeHashed() { return false; }
  2580. public function getCommandId() { return 'UNSUBSCRIBE'; }
  2581. }
  2582. class SubscribeByPattern extends Command {
  2583. public function canBeHashed() { return false; }
  2584. public function getCommandId() { return 'PSUBSCRIBE'; }
  2585. }
  2586. class UnsubscribeByPattern extends Command {
  2587. public function canBeHashed() { return false; }
  2588. public function getCommandId() { return 'PUNSUBSCRIBE'; }
  2589. }
  2590. class Publish extends Command {
  2591. public function canBeHashed() { return false; }
  2592. public function getCommandId() { return 'PUBLISH'; }
  2593. }
  2594. /* persistence control commands */
  2595. class Save extends Command {
  2596. public function canBeHashed() { return false; }
  2597. public function getCommandId() { return 'SAVE'; }
  2598. }
  2599. class BackgroundSave extends Command {
  2600. public function canBeHashed() { return false; }
  2601. public function getCommandId() { return 'BGSAVE'; }
  2602. public function parseResponse($data) {
  2603. if ($data == 'Background saving started') {
  2604. return true;
  2605. }
  2606. return $data;
  2607. }
  2608. }
  2609. class BackgroundRewriteAppendOnlyFile extends Command {
  2610. public function canBeHashed() { return false; }
  2611. public function getCommandId() { return 'BGREWRITEAOF'; }
  2612. public function parseResponse($data) {
  2613. return $data == 'Background append only file rewriting started';
  2614. }
  2615. }
  2616. class LastSave extends Command {
  2617. public function canBeHashed() { return false; }
  2618. public function getCommandId() { return 'LASTSAVE'; }
  2619. }
  2620. class Shutdown extends Command {
  2621. public function canBeHashed() { return false; }
  2622. public function getCommandId() { return 'SHUTDOWN'; }
  2623. public function closesConnection() { return true; }
  2624. }
  2625. /* remote server control commands */
  2626. class Info extends Command {
  2627. public function canBeHashed() { return false; }
  2628. public function getCommandId() { return 'INFO'; }
  2629. public function parseResponse($data) {
  2630. $info = array();
  2631. $infoLines = explode("\r\n", $data, -1);
  2632. foreach ($infoLines as $row) {
  2633. list($k, $v) = explode(':', $row);
  2634. if (!preg_match('/^db\d+$/', $k)) {
  2635. $info[$k] = $v;
  2636. }
  2637. else {
  2638. $db = array();
  2639. foreach (explode(',', $v) as $dbvar) {
  2640. list($dbvk, $dbvv) = explode('=', $dbvar);
  2641. $db[trim($dbvk)] = $dbvv;
  2642. }
  2643. $info[$k] = $db;
  2644. }
  2645. }
  2646. return $info;
  2647. }
  2648. }
  2649. class SlaveOf extends Command {
  2650. public function canBeHashed() { return false; }
  2651. public function getCommandId() { return 'SLAVEOF'; }
  2652. public function filterArguments(Array $arguments) {
  2653. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2654. return array('NO', 'ONE');
  2655. }
  2656. return $arguments;
  2657. }
  2658. }
  2659. class Config extends Command {
  2660. public function canBeHashed() { return false; }
  2661. public function getCommandId() { return 'CONFIG'; }
  2662. }
  2663. ?>