Predis.php 87 KB

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