Predis.php 77 KB

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