Predis.php 87 KB

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