Predis.php 99 KB

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