Predis.php 104 KB

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