Predis.php 103 KB

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