Predis.php 87 KB

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