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