Predis.php 72 KB

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