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