Predis.php 101 KB

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