Predis.php 104 KB

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