Predis.php 96 KB

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