Predis.php 76 KB

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