Predis.php 104 KB

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