Predis.php 76 KB

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