Predis.php 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  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. /* ------------------------------------------------------------------------- */
  694. class ConnectionParameters {
  695. const DEFAULT_HOST = '127.0.0.1';
  696. const DEFAULT_PORT = 6379;
  697. const DEFAULT_TIMEOUT = 5;
  698. private $_parameters;
  699. public function __construct($parameters = null) {
  700. $parameters = $parameters ?: array();
  701. $this->_parameters = is_array($parameters)
  702. ? self::filterConnectionParams($parameters)
  703. : self::parseURI($parameters);
  704. }
  705. private static function parseURI($uri) {
  706. $parsed = @parse_url($uri);
  707. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  708. throw new ClientException("Invalid URI: $uri");
  709. }
  710. if (array_key_exists('query', $parsed)) {
  711. $details = array();
  712. foreach (explode('&', $parsed['query']) as $kv) {
  713. list($k, $v) = explode('=', $kv);
  714. switch ($k) {
  715. case 'database':
  716. $details['database'] = $v;
  717. break;
  718. case 'password':
  719. $details['password'] = $v;
  720. break;
  721. case 'connection_async':
  722. $details['connection_async'] = $v;
  723. break;
  724. case 'connection_persistent':
  725. $details['connection_persistent'] = $v;
  726. break;
  727. case 'connection_timeout':
  728. $details['connection_timeout'] = $v;
  729. break;
  730. case 'read_write_timeout':
  731. $details['read_write_timeout'] = $v;
  732. break;
  733. case 'alias':
  734. $details['alias'] = $v;
  735. break;
  736. case 'weight':
  737. $details['weight'] = $v;
  738. break;
  739. }
  740. }
  741. $parsed = array_merge($parsed, $details);
  742. }
  743. return self::filterConnectionParams($parsed);
  744. }
  745. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  746. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  747. }
  748. private static function filterConnectionParams($parameters) {
  749. return array(
  750. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  751. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  752. 'database' => self::getParamOrDefault($parameters, 'database'),
  753. 'password' => self::getParamOrDefault($parameters, 'password'),
  754. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  755. 'connection_persistent' => self::getParamOrDefault($parameters, 'connection_persistent', false),
  756. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  757. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  758. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  759. 'weight' => self::getParamOrDefault($parameters, 'weight'),
  760. );
  761. }
  762. public function __get($parameter) {
  763. return $this->_parameters[$parameter];
  764. }
  765. public function __isset($parameter) {
  766. return isset($this->_parameters[$parameter]);
  767. }
  768. }
  769. interface IDistributionAlgorithm {
  770. public function add($node, $weight = null);
  771. public function remove($node);
  772. public function get($key);
  773. public function generateKey($value);
  774. }
  775. interface IConnection {
  776. public function connect();
  777. public function disconnect();
  778. public function isConnected();
  779. public function writeCommand(Command $command);
  780. public function readResponse(Command $command);
  781. public function executeCommand(Command $command);
  782. }
  783. class Connection implements IConnection {
  784. private $_params, $_socket, $_initCmds, $_reader;
  785. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  786. $this->_params = $parameters;
  787. $this->_initCmds = array();
  788. $this->_reader = $reader ?: new ResponseReader();
  789. }
  790. public function __destruct() {
  791. if (!$this->_params->connection_persistent) {
  792. $this->disconnect();
  793. }
  794. }
  795. public function isConnected() {
  796. return is_resource($this->_socket);
  797. }
  798. public function connect() {
  799. if ($this->isConnected()) {
  800. throw new ClientException('Connection already estabilished');
  801. }
  802. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  803. $connectFlags = STREAM_CLIENT_CONNECT;
  804. if ($this->_params->connection_async) {
  805. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  806. }
  807. if ($this->_params->connection_persistent) {
  808. $connectFlags |= STREAM_CLIENT_PERSISTENT;
  809. }
  810. $this->_socket = @stream_socket_client(
  811. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  812. );
  813. if (!$this->_socket) {
  814. $this->onCommunicationException(trim($errstr), $errno);
  815. }
  816. if (isset($this->_params->read_write_timeout)) {
  817. $timeoutSeconds = floor($this->_params->read_write_timeout);
  818. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  819. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  820. }
  821. if (count($this->_initCmds) > 0){
  822. $this->sendInitializationCommands();
  823. }
  824. }
  825. public function disconnect() {
  826. if ($this->isConnected()) {
  827. fclose($this->_socket);
  828. }
  829. }
  830. public function pushInitCommand(Command $command){
  831. $this->_initCmds[] = $command;
  832. }
  833. private function sendInitializationCommands() {
  834. foreach ($this->_initCmds as $command) {
  835. $this->writeCommand($command);
  836. }
  837. foreach ($this->_initCmds as $command) {
  838. $this->readResponse($command);
  839. }
  840. }
  841. private function onCommunicationException($message, $code = null) {
  842. Utilities\Shared::onCommunicationException(
  843. new CommunicationException($this, $message, $code)
  844. );
  845. }
  846. public function writeCommand(Command $command) {
  847. $this->writeBytes($command());
  848. }
  849. public function readResponse(Command $command) {
  850. $response = $this->_reader->read($this);
  851. $skipparse = isset($response->queued) || isset($response->error);
  852. return $skipparse ? $response : $command->parseResponse($response);
  853. }
  854. public function executeCommand(Command $command) {
  855. $this->writeCommand($command);
  856. if ($command->closesConnection()) {
  857. return $this->disconnect();
  858. }
  859. return $this->readResponse($command);
  860. }
  861. public function rawCommand($rawCommandData, $closesConnection = false) {
  862. $this->writeBytes($rawCommandData);
  863. if ($closesConnection) {
  864. $this->disconnect();
  865. return;
  866. }
  867. return $this->_reader->read($this);
  868. }
  869. public function writeBytes($value) {
  870. $socket = $this->getSocket();
  871. while (($length = strlen($value)) > 0) {
  872. $written = fwrite($socket, $value);
  873. if ($length === $written) {
  874. return true;
  875. }
  876. if ($written === false || $written === 0) {
  877. $this->onCommunicationException('Error while writing bytes to the server');
  878. }
  879. $value = substr($value, $written);
  880. }
  881. return true;
  882. }
  883. public function readBytes($length) {
  884. if ($length == 0) {
  885. throw new \InvalidArgumentException('Length parameter must be greater than 0');
  886. }
  887. $socket = $this->getSocket();
  888. $value = '';
  889. do {
  890. $chunk = fread($socket, $length);
  891. if ($chunk === false || $chunk === '') {
  892. $this->onCommunicationException('Error while reading bytes from the server');
  893. }
  894. $value .= $chunk;
  895. }
  896. while (($length -= strlen($chunk)) > 0);
  897. return $value;
  898. }
  899. public function readLine() {
  900. $socket = $this->getSocket();
  901. $value = '';
  902. do {
  903. $chunk = fgets($socket);
  904. if ($chunk === false || strlen($chunk) == 0) {
  905. $this->onCommunicationException('Error while reading line from the server');
  906. }
  907. $value .= $chunk;
  908. }
  909. while (substr($value, -2) !== Protocol::NEWLINE);
  910. return substr($value, 0, -2);
  911. }
  912. public function getSocket() {
  913. if (!$this->isConnected()) {
  914. $this->connect();
  915. }
  916. return $this->_socket;
  917. }
  918. public function getResponseReader() {
  919. return $this->_reader;
  920. }
  921. public function getParameters() {
  922. return $this->_params;
  923. }
  924. public function __toString() {
  925. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  926. }
  927. }
  928. class ConnectionCluster implements IConnection, \IteratorAggregate {
  929. private $_pool, $_distributor;
  930. public function __construct(IDistributionAlgorithm $distributor = null) {
  931. $this->_pool = array();
  932. $this->_distributor = $distributor ?: new Utilities\HashRing();
  933. }
  934. public function isConnected() {
  935. foreach ($this->_pool as $connection) {
  936. if ($connection->isConnected()) {
  937. return true;
  938. }
  939. }
  940. return false;
  941. }
  942. public function connect() {
  943. foreach ($this->_pool as $connection) {
  944. $connection->connect();
  945. }
  946. }
  947. public function disconnect() {
  948. foreach ($this->_pool as $connection) {
  949. $connection->disconnect();
  950. }
  951. }
  952. public function add(Connection $connection) {
  953. $parameters = $connection->getParameters();
  954. if (isset($parameters->alias)) {
  955. $this->_pool[$parameters->alias] = $connection;
  956. }
  957. else {
  958. $this->_pool[] = $connection;
  959. }
  960. $this->_distributor->add($connection, $parameters->weight);
  961. }
  962. public function getConnection(Command $command) {
  963. if ($command->canBeHashed() === false) {
  964. throw new ClientException(
  965. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  966. );
  967. }
  968. return $this->_distributor->get($command->getHash($this->_distributor));
  969. }
  970. public function getConnectionById($id = null) {
  971. return $this->_pool[$id ?: 0];
  972. }
  973. public function getIterator() {
  974. return new \ArrayIterator($this->_pool);
  975. }
  976. public function writeCommand(Command $command) {
  977. $this->getConnection($command)->writeCommand($command);
  978. }
  979. public function readResponse(Command $command) {
  980. return $this->getConnection($command)->readResponse($command);
  981. }
  982. public function executeCommand(Command $command) {
  983. $connection = $this->getConnection($command);
  984. $connection->writeCommand($command);
  985. return $connection->readResponse($command);
  986. }
  987. }
  988. /* ------------------------------------------------------------------------- */
  989. abstract class RedisServerProfile {
  990. private static $_serverProfiles;
  991. private $_registeredCommands;
  992. public function __construct() {
  993. $this->_registeredCommands = $this->getSupportedCommands();
  994. }
  995. public abstract function getVersion();
  996. protected abstract function getSupportedCommands();
  997. public static function getDefault() {
  998. return self::get('default');
  999. }
  1000. private static function predisServerProfiles() {
  1001. return array(
  1002. '1.2' => '\Predis\RedisServer_v1_2',
  1003. 'default' => '\Predis\RedisServer_v1_2',
  1004. 'dev' => '\Predis\RedisServer_vNext',
  1005. );
  1006. }
  1007. public static function registerProfile($profileClass, $aliases) {
  1008. if (!isset(self::$_serverProfiles)) {
  1009. self::$_serverProfiles = self::predisServerProfiles();
  1010. }
  1011. $profileReflection = new \ReflectionClass($profileClass);
  1012. if (!$profileReflection->isSubclassOf('\Predis\RedisServerProfile')) {
  1013. throw new ClientException("Cannot register '$profileClass' as it is not a valid profile class");
  1014. }
  1015. if (is_array($aliases)) {
  1016. foreach ($aliases as $alias) {
  1017. self::$_serverProfiles[$alias] = $profileClass;
  1018. }
  1019. }
  1020. else {
  1021. self::$_serverProfiles[$aliases] = $profileClass;
  1022. }
  1023. }
  1024. public static function get($version) {
  1025. if (!isset(self::$_serverProfiles)) {
  1026. self::$_serverProfiles = self::predisServerProfiles();
  1027. }
  1028. if (!isset(self::$_serverProfiles[$version])) {
  1029. throw new ClientException("Unknown server profile: $version");
  1030. }
  1031. $profile = self::$_serverProfiles[$version];
  1032. return new $profile();
  1033. }
  1034. public function compareWith($version, $operator = null) {
  1035. // one could expect that PHP's version_compare would behave
  1036. // the same way if invoked with 2 arguments or 3 arguments
  1037. // with the third being NULL, but it is not like that.
  1038. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  1039. // we might need to revise the behavior of this method.
  1040. return ($operator === null
  1041. ? version_compare($this, $version)
  1042. : version_compare($this, $version, $operator)
  1043. );
  1044. }
  1045. public function supportsCommand($command) {
  1046. return isset($this->_registeredCommands[$command]);
  1047. }
  1048. public function createCommand($method, $arguments = array()) {
  1049. if (!isset($this->_registeredCommands[$method])) {
  1050. throw new ClientException("'$method' is not a registered Redis command");
  1051. }
  1052. $commandClass = $this->_registeredCommands[$method];
  1053. $command = new $commandClass();
  1054. $command->setArgumentsArray($arguments);
  1055. return $command;
  1056. }
  1057. public function registerCommands(Array $commands) {
  1058. foreach ($commands as $command => $aliases) {
  1059. $this->registerCommand($command, $aliases);
  1060. }
  1061. }
  1062. public function registerCommand($command, $aliases) {
  1063. $commandReflection = new \ReflectionClass($command);
  1064. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  1065. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  1066. }
  1067. if (is_array($aliases)) {
  1068. foreach ($aliases as $alias) {
  1069. $this->_registeredCommands[$alias] = $command;
  1070. }
  1071. }
  1072. else {
  1073. $this->_registeredCommands[$aliases] = $command;
  1074. }
  1075. }
  1076. public function __toString() {
  1077. return $this->getVersion();
  1078. }
  1079. }
  1080. class RedisServer_v1_2 extends RedisServerProfile {
  1081. public function getVersion() { return '1.2'; }
  1082. public function getSupportedCommands() {
  1083. return array(
  1084. /* miscellaneous commands */
  1085. 'ping' => '\Predis\Commands\Ping',
  1086. 'echo' => '\Predis\Commands\DoEcho',
  1087. 'auth' => '\Predis\Commands\Auth',
  1088. /* connection handling */
  1089. 'quit' => '\Predis\Commands\Quit',
  1090. /* commands operating on string values */
  1091. 'set' => '\Predis\Commands\Set',
  1092. 'setnx' => '\Predis\Commands\SetPreserve',
  1093. 'setPreserve' => '\Predis\Commands\SetPreserve',
  1094. 'mset' => '\Predis\Commands\SetMultiple',
  1095. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1096. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1097. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1098. 'get' => '\Predis\Commands\Get',
  1099. 'mget' => '\Predis\Commands\GetMultiple',
  1100. 'getMultiple' => '\Predis\Commands\GetMultiple',
  1101. 'getset' => '\Predis\Commands\GetSet',
  1102. 'getSet' => '\Predis\Commands\GetSet',
  1103. 'incr' => '\Predis\Commands\Increment',
  1104. 'increment' => '\Predis\Commands\Increment',
  1105. 'incrby' => '\Predis\Commands\IncrementBy',
  1106. 'incrementBy' => '\Predis\Commands\IncrementBy',
  1107. 'decr' => '\Predis\Commands\Decrement',
  1108. 'decrement' => '\Predis\Commands\Decrement',
  1109. 'decrby' => '\Predis\Commands\DecrementBy',
  1110. 'decrementBy' => '\Predis\Commands\DecrementBy',
  1111. 'exists' => '\Predis\Commands\Exists',
  1112. 'del' => '\Predis\Commands\Delete',
  1113. 'delete' => '\Predis\Commands\Delete',
  1114. 'type' => '\Predis\Commands\Type',
  1115. /* commands operating on the key space */
  1116. 'keys' => '\Predis\Commands\Keys',
  1117. 'randomkey' => '\Predis\Commands\RandomKey',
  1118. 'randomKey' => '\Predis\Commands\RandomKey',
  1119. 'rename' => '\Predis\Commands\Rename',
  1120. 'renamenx' => '\Predis\Commands\RenamePreserve',
  1121. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  1122. 'expire' => '\Predis\Commands\Expire',
  1123. 'expireat' => '\Predis\Commands\ExpireAt',
  1124. 'expireAt' => '\Predis\Commands\ExpireAt',
  1125. 'dbsize' => '\Predis\Commands\DatabaseSize',
  1126. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  1127. 'ttl' => '\Predis\Commands\TimeToLive',
  1128. 'timeToLive' => '\Predis\Commands\TimeToLive',
  1129. /* commands operating on lists */
  1130. 'rpush' => '\Predis\Commands\ListPushTail',
  1131. 'pushTail' => '\Predis\Commands\ListPushTail',
  1132. 'lpush' => '\Predis\Commands\ListPushHead',
  1133. 'pushHead' => '\Predis\Commands\ListPushHead',
  1134. 'llen' => '\Predis\Commands\ListLength',
  1135. 'listLength' => '\Predis\Commands\ListLength',
  1136. 'lrange' => '\Predis\Commands\ListRange',
  1137. 'listRange' => '\Predis\Commands\ListRange',
  1138. 'ltrim' => '\Predis\Commands\ListTrim',
  1139. 'listTrim' => '\Predis\Commands\ListTrim',
  1140. 'lindex' => '\Predis\Commands\ListIndex',
  1141. 'listIndex' => '\Predis\Commands\ListIndex',
  1142. 'lset' => '\Predis\Commands\ListSet',
  1143. 'listSet' => '\Predis\Commands\ListSet',
  1144. 'lrem' => '\Predis\Commands\ListRemove',
  1145. 'listRemove' => '\Predis\Commands\ListRemove',
  1146. 'lpop' => '\Predis\Commands\ListPopFirst',
  1147. 'popFirst' => '\Predis\Commands\ListPopFirst',
  1148. 'rpop' => '\Predis\Commands\ListPopLast',
  1149. 'popLast' => '\Predis\Commands\ListPopLast',
  1150. 'rpoplpush' => '\Predis\Commands\ListPopLastPushHead',
  1151. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1152. /* commands operating on sets */
  1153. 'sadd' => '\Predis\Commands\SetAdd',
  1154. 'setAdd' => '\Predis\Commands\SetAdd',
  1155. 'srem' => '\Predis\Commands\SetRemove',
  1156. 'setRemove' => '\Predis\Commands\SetRemove',
  1157. 'spop' => '\Predis\Commands\SetPop',
  1158. 'setPop' => '\Predis\Commands\SetPop',
  1159. 'smove' => '\Predis\Commands\SetMove',
  1160. 'setMove' => '\Predis\Commands\SetMove',
  1161. 'scard' => '\Predis\Commands\SetCardinality',
  1162. 'setCardinality' => '\Predis\Commands\SetCardinality',
  1163. 'sismember' => '\Predis\Commands\SetIsMember',
  1164. 'setIsMember' => '\Predis\Commands\SetIsMember',
  1165. 'sinter' => '\Predis\Commands\SetIntersection',
  1166. 'setIntersection' => '\Predis\Commands\SetIntersection',
  1167. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1168. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  1169. 'sunion' => '\Predis\Commands\SetUnion',
  1170. 'setUnion' => '\Predis\Commands\SetUnion',
  1171. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1172. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  1173. 'sdiff' => '\Predis\Commands\SetDifference',
  1174. 'setDifference' => '\Predis\Commands\SetDifference',
  1175. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1176. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  1177. 'smembers' => '\Predis\Commands\SetMembers',
  1178. 'setMembers' => '\Predis\Commands\SetMembers',
  1179. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1180. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  1181. /* commands operating on sorted sets */
  1182. 'zadd' => '\Predis\Commands\ZSetAdd',
  1183. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1184. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1185. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1186. 'zrem' => '\Predis\Commands\ZSetRemove',
  1187. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1188. 'zrange' => '\Predis\Commands\ZSetRange',
  1189. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1190. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1191. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1192. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1193. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1194. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1195. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1196. 'zscore' => '\Predis\Commands\ZSetScore',
  1197. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1198. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1199. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1200. /* multiple databases handling commands */
  1201. 'select' => '\Predis\Commands\SelectDatabase',
  1202. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  1203. 'move' => '\Predis\Commands\MoveKey',
  1204. 'moveKey' => '\Predis\Commands\MoveKey',
  1205. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1206. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  1207. 'flushall' => '\Predis\Commands\FlushAll',
  1208. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1209. /* sorting */
  1210. 'sort' => '\Predis\Commands\Sort',
  1211. /* remote server control commands */
  1212. 'info' => '\Predis\Commands\Info',
  1213. 'slaveof' => '\Predis\Commands\SlaveOf',
  1214. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1215. /* persistence control commands */
  1216. 'save' => '\Predis\Commands\Save',
  1217. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1218. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1219. 'lastsave' => '\Predis\Commands\LastSave',
  1220. 'lastSave' => '\Predis\Commands\LastSave',
  1221. 'shutdown' => '\Predis\Commands\Shutdown',
  1222. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1223. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1224. );
  1225. }
  1226. }
  1227. class RedisServer_vNext extends RedisServer_v1_2 {
  1228. public function getVersion() { return '1.3'; }
  1229. public function getSupportedCommands() {
  1230. return array_merge(parent::getSupportedCommands(), array(
  1231. /* transactions */
  1232. 'multi' => '\Predis\Commands\Multi',
  1233. 'exec' => '\Predis\Commands\Exec',
  1234. 'discard' => '\Predis\Commands\Discard',
  1235. /* commands operating on string values */
  1236. 'setex' => '\Predis\Commands\SetExpire',
  1237. 'setExpire' => '\Predis\Commands\SetExpire',
  1238. 'append' => '\Predis\Commands\Append',
  1239. 'substr' => '\Predis\Commands\Substr',
  1240. /* commands operating on lists */
  1241. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1242. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1243. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1244. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1245. /* commands operating on sorted sets */
  1246. 'zunion' => '\Predis\Commands\ZSetUnion',
  1247. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1248. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1249. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1250. 'zcount' => '\Predis\Commands\ZSetCount',
  1251. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1252. 'zrank' => '\Predis\Commands\ZSetRank',
  1253. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1254. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1255. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1256. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1257. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1258. /* commands operating on hashes */
  1259. 'hset' => '\Predis\Commands\HashSet',
  1260. 'hashSet' => '\Predis\Commands\HashSet',
  1261. 'hsetnx' => '\Predis\Commands\HashSetPreserve',
  1262. 'hashSetPreserve' => '\Predis\Commands\HashSetPreserve',
  1263. 'hmset' => '\Predis\Commands\HashSetMultiple',
  1264. 'hashSetMultiple' => '\Predis\Commands\HashSetMultiple',
  1265. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1266. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1267. 'hget' => '\Predis\Commands\HashGet',
  1268. 'hashGet' => '\Predis\Commands\HashGet',
  1269. 'hmget' => '\Predis\Commands\HashGetMultiple',
  1270. 'hashGetMultiple' => '\Predis\Commands\HashGetMultiple',
  1271. 'hdel' => '\Predis\Commands\HashDelete',
  1272. 'hashDelete' => '\Predis\Commands\HashDelete',
  1273. 'hexists' => '\Predis\Commands\HashExists',
  1274. 'hashExists' => '\Predis\Commands\HashExists',
  1275. 'hlen' => '\Predis\Commands\HashLength',
  1276. 'hashLength' => '\Predis\Commands\HashLength',
  1277. 'hkeys' => '\Predis\Commands\HashKeys',
  1278. 'hashKeys' => '\Predis\Commands\HashKeys',
  1279. 'hvals' => '\Predis\Commands\HashValues',
  1280. 'hashValues' => '\Predis\Commands\HashValues',
  1281. 'hgetall' => '\Predis\Commands\HashGetAll',
  1282. 'hashGetAll' => '\Predis\Commands\HashGetAll',
  1283. /* publish - subscribe */
  1284. 'subscribe' => '\Predis\Commands\Subscribe',
  1285. 'unsubscribe' => '\Predis\Commands\Unsubscribe',
  1286. 'publish' => '\Predis\Commands\Publish',
  1287. /* remote server control commands */
  1288. 'config' => '\Predis\Commands\Config',
  1289. 'configuration' => '\Predis\Commands\Config',
  1290. ));
  1291. }
  1292. }
  1293. /* ------------------------------------------------------------------------- */
  1294. namespace Predis\Utilities;
  1295. class Shared {
  1296. public static function onCommunicationException(\Predis\CommunicationException $exception) {
  1297. if ($exception->shouldResetConnection()) {
  1298. $connection = $exception->getConnection();
  1299. if ($connection->isConnected()) {
  1300. $connection->disconnect();
  1301. }
  1302. }
  1303. throw $exception;
  1304. }
  1305. }
  1306. class HashRing implements \Predis\IDistributionAlgorithm {
  1307. const DEFAULT_REPLICAS = 128;
  1308. const DEFAULT_WEIGHT = 100;
  1309. private $_nodes, $_ring, $_ringKeys, $_ringKeysCount, $_replicas;
  1310. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1311. $this->_replicas = $replicas;
  1312. $this->_nodes = array();
  1313. }
  1314. public function add($node, $weight = null) {
  1315. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1316. // last wins, thus the order in which nodes are added is significant.
  1317. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT);
  1318. $this->reset();
  1319. }
  1320. public function remove($node) {
  1321. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1322. // scratch, in order to reassign possible hashes with collisions to the
  1323. // right node according to the order in which they were added in the
  1324. // first place.
  1325. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1326. if ($this->_nodes[$i]['object'] === $node) {
  1327. array_splice($this->_nodes, $i, 1);
  1328. $this->reset();
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. private function reset() {
  1334. unset($this->_ring);
  1335. unset($this->_ringKeys);
  1336. unset($this->_ringKeysCount);
  1337. }
  1338. private function isInitialized() {
  1339. return isset($this->_ringKeys);
  1340. }
  1341. private function computeTotalWeight() {
  1342. // TODO: array_reduce + lambda for PHP 5.3
  1343. $totalWeight = 0;
  1344. foreach ($this->_nodes as $node) {
  1345. $totalWeight += $node['weight'];
  1346. }
  1347. return $totalWeight;
  1348. }
  1349. private function initialize() {
  1350. if ($this->isInitialized()) {
  1351. return;
  1352. }
  1353. if (count($this->_nodes) === 0) {
  1354. throw new \LogicException('Cannot initialize empty hashring');
  1355. }
  1356. $this->_ring = array();
  1357. $totalWeight = $this->computeTotalWeight();
  1358. $nodesCount = count($this->_nodes);
  1359. foreach ($this->_nodes as $node) {
  1360. $weightRatio = $node['weight'] / $totalWeight;
  1361. $this->addNodeToRing($this->_ring, $node, $nodesCount, $this->_replicas, $weightRatio);
  1362. }
  1363. ksort($this->_ring, SORT_NUMERIC);
  1364. $this->_ringKeys = array_keys($this->_ring);
  1365. $this->_ringKeysCount = count($this->_ringKeys);
  1366. }
  1367. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1368. $nodeObject = $node['object'];
  1369. $nodeHash = (string) $nodeObject;
  1370. $replicas = (int) round($weightRatio * $totalNodes * $replicas);
  1371. for ($i = 0; $i < $replicas; $i++) {
  1372. $key = crc32("$nodeHash:$i");
  1373. $ring[$key] = $nodeObject;
  1374. }
  1375. }
  1376. public function generateKey($value) {
  1377. return crc32($value);
  1378. }
  1379. public function get($key) {
  1380. return $this->_ring[$this->getNodeKey($key)];
  1381. }
  1382. private function getNodeKey($key) {
  1383. $this->initialize();
  1384. $ringKeys = $this->_ringKeys;
  1385. $upper = $this->_ringKeysCount - 1;
  1386. $lower = 0;
  1387. while ($lower <= $upper) {
  1388. $index = ($lower + $upper) >> 1;
  1389. $item = $ringKeys[$index];
  1390. if ($item > $key) {
  1391. $upper = $index - 1;
  1392. }
  1393. else if ($item < $key) {
  1394. $lower = $index + 1;
  1395. }
  1396. else {
  1397. return $item;
  1398. }
  1399. }
  1400. return $ringKeys[$this->wrapAroundStrategy($upper, $lower, $this->_ringKeysCount)];
  1401. }
  1402. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1403. // NOTE: binary search for the last item in _ringkeys with a value
  1404. // less or equal to the key. If no such item exists, return the
  1405. // last item.
  1406. return $upper >= 0 ? $upper : $ringKeysCount - 1;
  1407. }
  1408. }
  1409. class KetamaPureRing extends HashRing {
  1410. const DEFAULT_REPLICAS = 160;
  1411. public function __construct() {
  1412. parent::__construct($this::DEFAULT_REPLICAS);
  1413. }
  1414. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) {
  1415. $nodeObject = $node['object'];
  1416. $nodeHash = (string) $nodeObject;
  1417. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  1418. for ($i = 0; $i < $replicas; $i++) {
  1419. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  1420. foreach ($unpackedDigest as $key) {
  1421. $ring[$key] = $nodeObject;
  1422. }
  1423. }
  1424. }
  1425. public function generateKey($value) {
  1426. $hash = unpack('V', md5($value, true));
  1427. return $hash[1];
  1428. }
  1429. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount) {
  1430. // NOTE: binary search for the first item in _ringkeys with a value
  1431. // greater or equal to the key. If no such item exists, return the
  1432. // first item.
  1433. return $lower < $ringKeysCount ? $lower : 0;
  1434. }
  1435. }
  1436. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1437. protected $_position, $_current, $_replySize;
  1438. public function rewind() {
  1439. // NOOP
  1440. }
  1441. public function current() {
  1442. return $this->_current;
  1443. }
  1444. public function key() {
  1445. return $this->_position;
  1446. }
  1447. public function next() {
  1448. if (++$this->_position < $this->_replySize) {
  1449. $this->_current = $this->getValue();
  1450. }
  1451. return $this->_position;
  1452. }
  1453. public function valid() {
  1454. return $this->_position < $this->_replySize;
  1455. }
  1456. public function count() {
  1457. // NOTE: use count if you want to get the size of the current multi-bulk
  1458. // response without using iterator_count (which actually consumes
  1459. // our iterator to calculate the size, and we cannot perform a rewind)
  1460. return $this->_replySize;
  1461. }
  1462. protected abstract function getValue();
  1463. }
  1464. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1465. private $_connection;
  1466. public function __construct(\Predis\Connection $connection, $size) {
  1467. $this->_connection = $connection;
  1468. $this->_reader = $connection->getResponseReader();
  1469. $this->_position = 0;
  1470. $this->_current = $size > 0 ? $this->getValue() : null;
  1471. $this->_replySize = $size;
  1472. }
  1473. public function __destruct() {
  1474. // when the iterator is garbage-collected (e.g. it goes out of the
  1475. // scope of a foreach) but it has not reached its end, we must sync
  1476. // the client with the queued elements that have not been read from
  1477. // the connection with the server.
  1478. $this->sync();
  1479. }
  1480. public function sync() {
  1481. while ($this->valid()) {
  1482. $this->next();
  1483. }
  1484. }
  1485. protected function getValue() {
  1486. return $this->_reader->read($this->_connection);
  1487. }
  1488. }
  1489. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1490. private $_iterator;
  1491. public function __construct(MultiBulkResponseIterator $iterator) {
  1492. $virtualSize = count($iterator) / 2;
  1493. $this->_iterator = $iterator;
  1494. $this->_position = 0;
  1495. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1496. $this->_replySize = $virtualSize;
  1497. }
  1498. public function __destruct() {
  1499. $this->_iterator->sync();
  1500. }
  1501. protected function getValue() {
  1502. $k = $this->_iterator->current();
  1503. $this->_iterator->next();
  1504. $v = $this->_iterator->current();
  1505. $this->_iterator->next();
  1506. return array($k, $v);
  1507. }
  1508. }
  1509. /* ------------------------------------------------------------------------- */
  1510. namespace Predis\Commands;
  1511. /* miscellaneous commands */
  1512. class Ping extends \Predis\MultiBulkCommand {
  1513. public function canBeHashed() { return false; }
  1514. public function getCommandId() { return 'PING'; }
  1515. public function parseResponse($data) {
  1516. return $data === 'PONG' ? true : false;
  1517. }
  1518. }
  1519. class DoEcho extends \Predis\MultiBulkCommand {
  1520. public function canBeHashed() { return false; }
  1521. public function getCommandId() { return 'ECHO'; }
  1522. }
  1523. class Auth extends \Predis\MultiBulkCommand {
  1524. public function canBeHashed() { return false; }
  1525. public function getCommandId() { return 'AUTH'; }
  1526. }
  1527. /* connection handling */
  1528. class Quit extends \Predis\MultiBulkCommand {
  1529. public function canBeHashed() { return false; }
  1530. public function getCommandId() { return 'QUIT'; }
  1531. public function closesConnection() { return true; }
  1532. }
  1533. /* commands operating on string values */
  1534. class Set extends \Predis\MultiBulkCommand {
  1535. public function getCommandId() { return 'SET'; }
  1536. }
  1537. class SetExpire extends \Predis\MultiBulkCommand {
  1538. public function getCommandId() { return 'SETEX'; }
  1539. }
  1540. class SetPreserve extends \Predis\MultiBulkCommand {
  1541. public function getCommandId() { return 'SETNX'; }
  1542. public function parseResponse($data) { return (bool) $data; }
  1543. }
  1544. class SetMultiple extends \Predis\MultiBulkCommand {
  1545. public function canBeHashed() { return false; }
  1546. public function getCommandId() { return 'MSET'; }
  1547. public function filterArguments(Array $arguments) {
  1548. if (count($arguments) === 1 && is_array($arguments[0])) {
  1549. $flattenedKVs = array();
  1550. $args = &$arguments[0];
  1551. foreach ($args as $k => $v) {
  1552. $flattenedKVs[] = $k;
  1553. $flattenedKVs[] = $v;
  1554. }
  1555. return $flattenedKVs;
  1556. }
  1557. return $arguments;
  1558. }
  1559. }
  1560. class SetMultiplePreserve extends \Predis\Commands\SetMultiple {
  1561. public function canBeHashed() { return false; }
  1562. public function getCommandId() { return 'MSETNX'; }
  1563. public function parseResponse($data) { return (bool) $data; }
  1564. }
  1565. class Get extends \Predis\MultiBulkCommand {
  1566. public function getCommandId() { return 'GET'; }
  1567. }
  1568. class GetMultiple extends \Predis\MultiBulkCommand {
  1569. public function canBeHashed() { return false; }
  1570. public function getCommandId() { return 'MGET'; }
  1571. }
  1572. class GetSet extends \Predis\MultiBulkCommand {
  1573. public function getCommandId() { return 'GETSET'; }
  1574. }
  1575. class Increment extends \Predis\MultiBulkCommand {
  1576. public function getCommandId() { return 'INCR'; }
  1577. }
  1578. class IncrementBy extends \Predis\MultiBulkCommand {
  1579. public function getCommandId() { return 'INCRBY'; }
  1580. }
  1581. class Decrement extends \Predis\MultiBulkCommand {
  1582. public function getCommandId() { return 'DECR'; }
  1583. }
  1584. class DecrementBy extends \Predis\MultiBulkCommand {
  1585. public function getCommandId() { return 'DECRBY'; }
  1586. }
  1587. class Exists extends \Predis\MultiBulkCommand {
  1588. public function getCommandId() { return 'EXISTS'; }
  1589. public function parseResponse($data) { return (bool) $data; }
  1590. }
  1591. class Delete extends \Predis\MultiBulkCommand {
  1592. public function getCommandId() { return 'DEL'; }
  1593. }
  1594. class Type extends \Predis\MultiBulkCommand {
  1595. public function getCommandId() { return 'TYPE'; }
  1596. }
  1597. class Append extends \Predis\MultiBulkCommand {
  1598. public function getCommandId() { return 'APPEND'; }
  1599. }
  1600. class Substr extends \Predis\MultiBulkCommand {
  1601. public function getCommandId() { return 'SUBSTR'; }
  1602. }
  1603. /* commands operating on the key space */
  1604. class Keys extends \Predis\MultiBulkCommand {
  1605. public function canBeHashed() { return false; }
  1606. public function getCommandId() { return 'KEYS'; }
  1607. public function parseResponse($data) {
  1608. // TODO: is this behaviour correct?
  1609. if (is_array($data) || $data instanceof \Iterator) {
  1610. return $data;
  1611. }
  1612. return strlen($data) > 0 ? explode(' ', $data) : array();
  1613. }
  1614. }
  1615. class RandomKey extends \Predis\MultiBulkCommand {
  1616. public function canBeHashed() { return false; }
  1617. public function getCommandId() { return 'RANDOMKEY'; }
  1618. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1619. }
  1620. class Rename extends \Predis\MultiBulkCommand {
  1621. public function canBeHashed() { return false; }
  1622. public function getCommandId() { return 'RENAME'; }
  1623. }
  1624. class RenamePreserve extends \Predis\MultiBulkCommand {
  1625. public function canBeHashed() { return false; }
  1626. public function getCommandId() { return 'RENAMENX'; }
  1627. public function parseResponse($data) { return (bool) $data; }
  1628. }
  1629. class Expire extends \Predis\MultiBulkCommand {
  1630. public function getCommandId() { return 'EXPIRE'; }
  1631. public function parseResponse($data) { return (bool) $data; }
  1632. }
  1633. class ExpireAt extends \Predis\MultiBulkCommand {
  1634. public function getCommandId() { return 'EXPIREAT'; }
  1635. public function parseResponse($data) { return (bool) $data; }
  1636. }
  1637. class DatabaseSize extends \Predis\MultiBulkCommand {
  1638. public function canBeHashed() { return false; }
  1639. public function getCommandId() { return 'DBSIZE'; }
  1640. }
  1641. class TimeToLive extends \Predis\MultiBulkCommand {
  1642. public function getCommandId() { return 'TTL'; }
  1643. }
  1644. /* commands operating on lists */
  1645. class ListPushTail extends \Predis\MultiBulkCommand {
  1646. public function getCommandId() { return 'RPUSH'; }
  1647. }
  1648. class ListPushHead extends \Predis\MultiBulkCommand {
  1649. public function getCommandId() { return 'LPUSH'; }
  1650. }
  1651. class ListLength extends \Predis\MultiBulkCommand {
  1652. public function getCommandId() { return 'LLEN'; }
  1653. }
  1654. class ListRange extends \Predis\MultiBulkCommand {
  1655. public function getCommandId() { return 'LRANGE'; }
  1656. }
  1657. class ListTrim extends \Predis\MultiBulkCommand {
  1658. public function getCommandId() { return 'LTRIM'; }
  1659. }
  1660. class ListIndex extends \Predis\MultiBulkCommand {
  1661. public function getCommandId() { return 'LINDEX'; }
  1662. }
  1663. class ListSet extends \Predis\MultiBulkCommand {
  1664. public function getCommandId() { return 'LSET'; }
  1665. }
  1666. class ListRemove extends \Predis\MultiBulkCommand {
  1667. public function getCommandId() { return 'LREM'; }
  1668. }
  1669. class ListPopLastPushHead extends \Predis\MultiBulkCommand {
  1670. public function getCommandId() { return 'RPOPLPUSH'; }
  1671. }
  1672. class ListPopLastPushHeadBulk extends \Predis\MultiBulkCommand {
  1673. public function getCommandId() { return 'RPOPLPUSH'; }
  1674. }
  1675. class ListPopFirst extends \Predis\MultiBulkCommand {
  1676. public function getCommandId() { return 'LPOP'; }
  1677. }
  1678. class ListPopLast extends \Predis\MultiBulkCommand {
  1679. public function getCommandId() { return 'RPOP'; }
  1680. }
  1681. class ListPopFirstBlocking extends \Predis\MultiBulkCommand {
  1682. public function getCommandId() { return 'BLPOP'; }
  1683. }
  1684. class ListPopLastBlocking extends \Predis\MultiBulkCommand {
  1685. public function getCommandId() { return 'BRPOP'; }
  1686. }
  1687. /* commands operating on sets */
  1688. class SetAdd extends \Predis\MultiBulkCommand {
  1689. public function getCommandId() { return 'SADD'; }
  1690. public function parseResponse($data) { return (bool) $data; }
  1691. }
  1692. class SetRemove extends \Predis\MultiBulkCommand {
  1693. public function getCommandId() { return 'SREM'; }
  1694. public function parseResponse($data) { return (bool) $data; }
  1695. }
  1696. class SetPop extends \Predis\MultiBulkCommand {
  1697. public function getCommandId() { return 'SPOP'; }
  1698. }
  1699. class SetMove extends \Predis\MultiBulkCommand {
  1700. public function canBeHashed() { return false; }
  1701. public function getCommandId() { return 'SMOVE'; }
  1702. public function parseResponse($data) { return (bool) $data; }
  1703. }
  1704. class SetCardinality extends \Predis\MultiBulkCommand {
  1705. public function getCommandId() { return 'SCARD'; }
  1706. }
  1707. class SetIsMember extends \Predis\MultiBulkCommand {
  1708. public function getCommandId() { return 'SISMEMBER'; }
  1709. public function parseResponse($data) { return (bool) $data; }
  1710. }
  1711. class SetIntersection extends \Predis\MultiBulkCommand {
  1712. public function getCommandId() { return 'SINTER'; }
  1713. }
  1714. class SetIntersectionStore extends \Predis\MultiBulkCommand {
  1715. public function getCommandId() { return 'SINTERSTORE'; }
  1716. }
  1717. class SetUnion extends \Predis\MultiBulkCommand {
  1718. public function getCommandId() { return 'SUNION'; }
  1719. }
  1720. class SetUnionStore extends \Predis\MultiBulkCommand {
  1721. public function getCommandId() { return 'SUNIONSTORE'; }
  1722. }
  1723. class SetDifference extends \Predis\MultiBulkCommand {
  1724. public function getCommandId() { return 'SDIFF'; }
  1725. }
  1726. class SetDifferenceStore extends \Predis\MultiBulkCommand {
  1727. public function getCommandId() { return 'SDIFFSTORE'; }
  1728. }
  1729. class SetMembers extends \Predis\MultiBulkCommand {
  1730. public function getCommandId() { return 'SMEMBERS'; }
  1731. }
  1732. class SetRandomMember extends \Predis\MultiBulkCommand {
  1733. public function getCommandId() { return 'SRANDMEMBER'; }
  1734. }
  1735. /* commands operating on sorted sets */
  1736. class ZSetAdd extends \Predis\MultiBulkCommand {
  1737. public function getCommandId() { return 'ZADD'; }
  1738. public function parseResponse($data) { return (bool) $data; }
  1739. }
  1740. class ZSetIncrementBy extends \Predis\MultiBulkCommand {
  1741. public function getCommandId() { return 'ZINCRBY'; }
  1742. }
  1743. class ZSetRemove extends \Predis\MultiBulkCommand {
  1744. public function getCommandId() { return 'ZREM'; }
  1745. public function parseResponse($data) { return (bool) $data; }
  1746. }
  1747. class ZSetUnion extends \Predis\MultiBulkCommand {
  1748. public function getCommandId() { return 'ZUNION'; }
  1749. public function filterArguments(Array $arguments) {
  1750. $options = array();
  1751. $argc = count($arguments);
  1752. if ($argc > 1 && is_array($arguments[$argc - 1])) {
  1753. $options = $this->prepareOptions(array_pop($arguments));
  1754. }
  1755. $args = is_array($arguments[0]) ? $arguments[0] : $arguments;
  1756. return array_merge($args, $options);
  1757. }
  1758. private function prepareOptions($options) {
  1759. $opts = array_change_key_case($options, CASE_UPPER);
  1760. $finalizedOpts = array();
  1761. if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
  1762. $finalizedOpts[] = 'WEIGHTS';
  1763. $finalizedOpts[] = $opts['WEIGHTS'][0];
  1764. $finalizedOpts[] = $opts['WEIGHTS'][1];
  1765. }
  1766. if (isset($opts['AGGREGATE'])) {
  1767. $finalizedOpts[] = 'AGGREGATE';
  1768. $finalizedOpts[] = $opts['AGGREGATE'];
  1769. }
  1770. return $finalizedOpts;
  1771. }
  1772. }
  1773. class ZSetIntersection extends \Predis\Commands\ZSetUnion {
  1774. public function getCommandId() { return 'ZINTER'; }
  1775. }
  1776. class ZSetRange extends \Predis\MultiBulkCommand {
  1777. public function getCommandId() { return 'ZRANGE'; }
  1778. public function parseResponse($data) {
  1779. $arguments = $this->getArguments();
  1780. if (count($arguments) === 4) {
  1781. if (strtolower($arguments[3]) === 'withscores') {
  1782. if ($data instanceof \Iterator) {
  1783. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1784. }
  1785. $result = array();
  1786. for ($i = 0; $i < count($data); $i++) {
  1787. $result[] = array($data[$i], $data[++$i]);
  1788. }
  1789. return $result;
  1790. }
  1791. }
  1792. return $data;
  1793. }
  1794. }
  1795. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1796. public function getCommandId() { return 'ZREVRANGE'; }
  1797. }
  1798. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1799. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1800. }
  1801. class ZSetCount extends \Predis\MultiBulkCommand {
  1802. public function getCommandId() { return 'ZCOUNT'; }
  1803. }
  1804. class ZSetCardinality extends \Predis\MultiBulkCommand {
  1805. public function getCommandId() { return 'ZCARD'; }
  1806. }
  1807. class ZSetScore extends \Predis\MultiBulkCommand {
  1808. public function getCommandId() { return 'ZSCORE'; }
  1809. }
  1810. class ZSetRemoveRangeByScore extends \Predis\MultiBulkCommand {
  1811. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1812. }
  1813. class ZSetRank extends \Predis\MultiBulkCommand {
  1814. public function getCommandId() { return 'ZRANK'; }
  1815. }
  1816. class ZSetReverseRank extends \Predis\MultiBulkCommand {
  1817. public function getCommandId() { return 'ZREVRANK'; }
  1818. }
  1819. class ZSetRemoveRangeByRank extends \Predis\MultiBulkCommand {
  1820. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1821. }
  1822. /* commands operating on hashes */
  1823. class HashSet extends \Predis\MultiBulkCommand {
  1824. public function getCommandId() { return 'HSET'; }
  1825. public function parseResponse($data) { return (bool) $data; }
  1826. }
  1827. class HashSetPreserve extends \Predis\MultiBulkCommand {
  1828. public function getCommandId() { return 'HSETNX'; }
  1829. public function parseResponse($data) { return (bool) $data; }
  1830. }
  1831. class HashSetMultiple extends \Predis\MultiBulkCommand {
  1832. public function getCommandId() { return 'HMSET'; }
  1833. public function filterArguments(Array $arguments) {
  1834. if (count($arguments) === 2 && is_array($arguments[1])) {
  1835. $flattenedKVs = array($arguments[0]);
  1836. $args = &$arguments[1];
  1837. foreach ($args as $k => $v) {
  1838. $flattenedKVs[] = $k;
  1839. $flattenedKVs[] = $v;
  1840. }
  1841. return $flattenedKVs;
  1842. }
  1843. return $arguments;
  1844. }
  1845. }
  1846. class HashIncrementBy extends \Predis\MultiBulkCommand {
  1847. public function getCommandId() { return 'HINCRBY'; }
  1848. }
  1849. class HashGet extends \Predis\MultiBulkCommand {
  1850. public function getCommandId() { return 'HGET'; }
  1851. }
  1852. class HashGetMultiple extends \Predis\MultiBulkCommand {
  1853. public function getCommandId() { return 'HMGET'; }
  1854. public function filterArguments(Array $arguments) {
  1855. if (count($arguments) === 2 && is_array($arguments[1])) {
  1856. $flattenedKVs = array($arguments[0]);
  1857. $args = &$arguments[1];
  1858. foreach ($args as $v) {
  1859. $flattenedKVs[] = $v;
  1860. }
  1861. return $flattenedKVs;
  1862. }
  1863. return $arguments;
  1864. }
  1865. }
  1866. class HashDelete extends \Predis\MultiBulkCommand {
  1867. public function getCommandId() { return 'HDEL'; }
  1868. public function parseResponse($data) { return (bool) $data; }
  1869. }
  1870. class HashExists extends \Predis\MultiBulkCommand {
  1871. public function getCommandId() { return 'HEXISTS'; }
  1872. public function parseResponse($data) { return (bool) $data; }
  1873. }
  1874. class HashLength extends \Predis\MultiBulkCommand {
  1875. public function getCommandId() { return 'HLEN'; }
  1876. }
  1877. class HashKeys extends \Predis\MultiBulkCommand {
  1878. public function getCommandId() { return 'HKEYS'; }
  1879. }
  1880. class HashValues extends \Predis\MultiBulkCommand {
  1881. public function getCommandId() { return 'HVALS'; }
  1882. }
  1883. class HashGetAll extends \Predis\MultiBulkCommand {
  1884. public function getCommandId() { return 'HGETALL'; }
  1885. public function parseResponse($data) {
  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[$data[$i]] = $data[++$i];
  1892. }
  1893. return $result;
  1894. }
  1895. }
  1896. /* multiple databases handling commands */
  1897. class SelectDatabase extends \Predis\MultiBulkCommand {
  1898. public function canBeHashed() { return false; }
  1899. public function getCommandId() { return 'SELECT'; }
  1900. }
  1901. class MoveKey extends \Predis\MultiBulkCommand {
  1902. public function canBeHashed() { return false; }
  1903. public function getCommandId() { return 'MOVE'; }
  1904. public function parseResponse($data) { return (bool) $data; }
  1905. }
  1906. class FlushDatabase extends \Predis\MultiBulkCommand {
  1907. public function canBeHashed() { return false; }
  1908. public function getCommandId() { return 'FLUSHDB'; }
  1909. }
  1910. class FlushAll extends \Predis\MultiBulkCommand {
  1911. public function canBeHashed() { return false; }
  1912. public function getCommandId() { return 'FLUSHALL'; }
  1913. }
  1914. /* sorting */
  1915. class Sort extends \Predis\MultiBulkCommand {
  1916. public function getCommandId() { return 'SORT'; }
  1917. public function filterArguments(Array $arguments) {
  1918. if (count($arguments) === 1) {
  1919. return $arguments;
  1920. }
  1921. // TODO: add more parameters checks
  1922. $query = array($arguments[0]);
  1923. $sortParams = $arguments[1];
  1924. if (isset($sortParams['by'])) {
  1925. $query[] = 'BY';
  1926. $query[] = $sortParams['by'];
  1927. }
  1928. if (isset($sortParams['get'])) {
  1929. $getargs = $sortParams['get'];
  1930. if (is_array($getargs)) {
  1931. foreach ($getargs as $getarg) {
  1932. $query[] = 'GET';
  1933. $query[] = $getarg;
  1934. }
  1935. }
  1936. else {
  1937. $query[] = 'GET';
  1938. $query[] = $getargs;
  1939. }
  1940. }
  1941. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1942. $query[] = 'LIMIT';
  1943. $query[] = $sortParams['limit'][0];
  1944. $query[] = $sortParams['limit'][1];
  1945. }
  1946. if (isset($sortParams['sort'])) {
  1947. $query[] = strtoupper($sortParams['sort']);
  1948. }
  1949. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1950. $query[] = 'ALPHA';
  1951. }
  1952. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1953. $query[] = 'STORE';
  1954. $query[] = $sortParams['store'];
  1955. }
  1956. return $query;
  1957. }
  1958. }
  1959. /* transactions */
  1960. class Multi extends \Predis\MultiBulkCommand {
  1961. public function canBeHashed() { return false; }
  1962. public function getCommandId() { return 'MULTI'; }
  1963. }
  1964. class Exec extends \Predis\MultiBulkCommand {
  1965. public function canBeHashed() { return false; }
  1966. public function getCommandId() { return 'EXEC'; }
  1967. }
  1968. class Discard extends \Predis\MultiBulkCommand {
  1969. public function canBeHashed() { return false; }
  1970. public function getCommandId() { return 'DISCARD'; }
  1971. }
  1972. /* publish/subscribe */
  1973. class Subscribe extends \Predis\MultiBulkCommand {
  1974. public function canBeHashed() { return false; }
  1975. public function getCommandId() { return 'SUBSCRIBE'; }
  1976. }
  1977. class Unsubscribe extends \Predis\MultiBulkCommand {
  1978. public function canBeHashed() { return false; }
  1979. public function getCommandId() { return 'UNSUBSCRIBE'; }
  1980. }
  1981. class Publish extends \Predis\MultiBulkCommand {
  1982. public function canBeHashed() { return false; }
  1983. public function getCommandId() { return 'PUBLISH'; }
  1984. }
  1985. /* persistence control commands */
  1986. class Save extends \Predis\MultiBulkCommand {
  1987. public function canBeHashed() { return false; }
  1988. public function getCommandId() { return 'SAVE'; }
  1989. }
  1990. class BackgroundSave extends \Predis\MultiBulkCommand {
  1991. public function canBeHashed() { return false; }
  1992. public function getCommandId() { return 'BGSAVE'; }
  1993. public function parseResponse($data) {
  1994. if ($data == 'Background saving started') {
  1995. return true;
  1996. }
  1997. return $data;
  1998. }
  1999. }
  2000. class BackgroundRewriteAppendOnlyFile extends \Predis\MultiBulkCommand {
  2001. public function canBeHashed() { return false; }
  2002. public function getCommandId() { return 'BGREWRITEAOF'; }
  2003. public function parseResponse($data) {
  2004. return $data == 'Background append only file rewriting started';
  2005. }
  2006. }
  2007. class LastSave extends \Predis\MultiBulkCommand {
  2008. public function canBeHashed() { return false; }
  2009. public function getCommandId() { return 'LASTSAVE'; }
  2010. }
  2011. class Shutdown extends \Predis\MultiBulkCommand {
  2012. public function canBeHashed() { return false; }
  2013. public function getCommandId() { return 'SHUTDOWN'; }
  2014. public function closesConnection() { return true; }
  2015. }
  2016. /* remote server control commands */
  2017. class Info extends \Predis\MultiBulkCommand {
  2018. public function canBeHashed() { return false; }
  2019. public function getCommandId() { return 'INFO'; }
  2020. public function parseResponse($data) {
  2021. $info = array();
  2022. $infoLines = explode("\r\n", $data, -1);
  2023. foreach ($infoLines as $row) {
  2024. list($k, $v) = explode(':', $row);
  2025. if (!preg_match('/^db\d+$/', $k)) {
  2026. $info[$k] = $v;
  2027. }
  2028. else {
  2029. $db = array();
  2030. foreach (explode(',', $v) as $dbvar) {
  2031. list($dbvk, $dbvv) = explode('=', $dbvar);
  2032. $db[trim($dbvk)] = $dbvv;
  2033. }
  2034. $info[$k] = $db;
  2035. }
  2036. }
  2037. return $info;
  2038. }
  2039. }
  2040. class SlaveOf extends \Predis\MultiBulkCommand {
  2041. public function canBeHashed() { return false; }
  2042. public function getCommandId() { return 'SLAVEOF'; }
  2043. public function filterArguments(Array $arguments) {
  2044. if (count($arguments) === 0 || $arguments[0] === 'NO ONE') {
  2045. return array('NO', 'ONE');
  2046. }
  2047. return $arguments;
  2048. }
  2049. }
  2050. class Config extends \Predis\MultiBulkCommand {
  2051. public function canBeHashed() { return false; }
  2052. public function getCommandId() { return 'CONFIG'; }
  2053. }
  2054. ?>