Predis.php 93 KB

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