Predis.php 94 KB

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