Predis.php 99 KB

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