Predis.php 104 KB

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