Predis.php 74 KB

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