Predis.php 109 KB

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