Predis.php 112 KB

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