Predis.php 108 KB

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