Predis.php 95 KB

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