Predis.php 99 KB

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