Predis.php 78 KB

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