Predis.php 99 KB

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