Predis.php 61 KB

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