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