Predis.php 104 KB

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