Predis.php 104 KB

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