Predis.php 101 KB

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