Predis.php 100 KB

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