Predis.php 102 KB

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