Predis.php 94 KB

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