Predis.php 94 KB

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