Predis.php 114 KB

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