Predis.php 98 KB

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