Predis.php 104 KB

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