Predis.php 108 KB

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