Predis.php 95 KB

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