Predis.php 98 KB

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