Predis.php 74 KB

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