Predis.php 95 KB

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