Predis.php 109 KB

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