Predis.php 108 KB

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