Predis.php 94 KB

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