Predis.php 95 KB

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