Predis.php 109 KB

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