Predis.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  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 ResponseIntegerHandler implements IResponseHandler {
  287. public function handle(ResponseReader $reader, $socket, $number) {
  288. if (is_numeric($number)) {
  289. return (int) $number;
  290. }
  291. else {
  292. if ($number !== ResponseReader::NULL) {
  293. throw new ClientException("Cannot parse '$number' as numeric response");
  294. }
  295. return null;
  296. }
  297. }
  298. }
  299. class ResponseReader {
  300. const NEWLINE = "\r\n";
  301. const OK = 'OK';
  302. const ERROR = 'ERR';
  303. const QUEUED = 'QUEUED';
  304. const NULL = 'nil';
  305. private $_prefixHandlers;
  306. public function __construct() {
  307. $this->initializePrefixHandlers();
  308. }
  309. private function initializePrefixHandlers() {
  310. $this->_prefixHandlers = array(
  311. '+' => new ResponseStatusHandler(),
  312. '-' => new ResponseErrorHandler(),
  313. ':' => new ResponseIntegerHandler(),
  314. '$' => new ResponseBulkHandler(),
  315. '*' => new ResponseMultiBulkHandler()
  316. );
  317. }
  318. private function setHandler($prefix, IResponseHandler $handler) {
  319. $this->_prefixHandlers[$prefix] = $handler;
  320. }
  321. public function setOption($option, $value) {
  322. switch ($option) {
  323. default:
  324. throw new \InvalidArgumentException("Unknown option: $option");
  325. }
  326. }
  327. public function getOption($option) {
  328. switch ($option) {
  329. default:
  330. throw new \InvalidArgumentException("Unknown option: $option");
  331. }
  332. }
  333. public function read($socket) {
  334. $header = fgets($socket);
  335. if ($header === false) {
  336. throw new ClientException('An error has occurred while reading from the network stream');
  337. }
  338. $prefix = $header[0];
  339. $payload = substr($header, 1, -2);
  340. if (!isset($this->_prefixHandlers[$prefix])) {
  341. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  342. }
  343. $handler = $this->_prefixHandlers[$prefix];
  344. return $handler->handle($this, $socket, $payload);
  345. }
  346. }
  347. class ResponseQueued {
  348. public $queued = true;
  349. public function __toString() {
  350. return ResponseReader::QUEUED;
  351. }
  352. }
  353. /* ------------------------------------------------------------------------- */
  354. class CommandPipeline {
  355. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  356. public function __construct(Client $redisClient) {
  357. $this->_redisClient = $redisClient;
  358. $this->_pipelineBuffer = array();
  359. $this->_returnValues = array();
  360. }
  361. public function __call($method, $arguments) {
  362. $command = $this->_redisClient->createCommand($method, $arguments);
  363. $this->recordCommand($command);
  364. return $this;
  365. }
  366. private function recordCommand(Command $command) {
  367. $this->_pipelineBuffer[] = $command;
  368. }
  369. private function getRecordedCommands() {
  370. return $this->_pipelineBuffer;
  371. }
  372. public function flushPipeline() {
  373. $sizeofPipe = count($this->_pipelineBuffer);
  374. if ($sizeofPipe === 0) {
  375. return;
  376. }
  377. $connection = $this->_redisClient->getConnection();
  378. $commands = &$this->_pipelineBuffer;
  379. foreach ($commands as $command) {
  380. $connection->writeCommand($command);
  381. }
  382. for ($i = 0; $i < $sizeofPipe; $i++) {
  383. $this->_returnValues[] = $connection->readResponse($commands[$i]);
  384. unset($commands[$i]);
  385. }
  386. $this->_pipelineBuffer = array();
  387. return $this;
  388. }
  389. private function setRunning($bool) {
  390. if ($bool == true && $this->_running == true) {
  391. throw new ClientException("This pipeline is already opened");
  392. }
  393. $this->_running = $bool;
  394. }
  395. public function execute($block = null) {
  396. if ($block && !is_callable($block)) {
  397. throw new \RuntimeException('Argument passed must be a callable object');
  398. }
  399. $this->setRunning(true);
  400. $pipelineBlockException = null;
  401. try {
  402. if ($block !== null) {
  403. $block($this);
  404. }
  405. $this->flushPipeline();
  406. }
  407. catch (\Exception $exception) {
  408. $pipelineBlockException = $exception;
  409. }
  410. $this->setRunning(false);
  411. if ($pipelineBlockException !== null) {
  412. throw $pipelineBlockException;
  413. }
  414. return $this->_returnValues;
  415. }
  416. }
  417. class MultiExecBlock {
  418. private $_redisClient, $_commands, $_initialized;
  419. public function __construct(Client $redisClient) {
  420. $this->_initialized = false;
  421. $this->_redisClient = $redisClient;
  422. $this->_commands = array();
  423. }
  424. private function initialize() {
  425. if ($this->_initialized === false) {
  426. $this->_redisClient->multi();
  427. $this->_initialized = true;
  428. }
  429. }
  430. public function __call($method, $arguments) {
  431. $this->initialize();
  432. $command = $this->_redisClient->createCommand($method, $arguments);
  433. $response = $this->_redisClient->executeCommand($command);
  434. if (isset($response->queued)) {
  435. $this->_commands[] = $command;
  436. return $this;
  437. }
  438. else {
  439. throw new ClientException('The server did not respond with a QUEUED status reply');
  440. }
  441. }
  442. public function execute($block = null) {
  443. if ($block && !is_callable($block)) {
  444. throw new \RuntimeException('Argument passed must be a callable object');
  445. }
  446. $blockException = null;
  447. $returnValues = array();
  448. try {
  449. if ($block !== null) {
  450. $block($this);
  451. }
  452. $execReply = $this->_redisClient->exec();
  453. $commands = &$this->_commands;
  454. $sizeofReplies = count($execReply);
  455. if ($sizeofReplies !== count($commands)) {
  456. // TODO: think of a better exception message
  457. throw new ClientException("Out-of-sync");
  458. }
  459. for ($i = 0; $i < $sizeofReplies; $i++) {
  460. $returnValues[] = $commands[$i]->parseResponse($execReply[$i]);
  461. unset($commands[$i]);
  462. }
  463. }
  464. catch (\Exception $exception) {
  465. $blockException = $exception;
  466. }
  467. if ($blockException !== null) {
  468. throw $blockException;
  469. }
  470. return $returnValues;
  471. }
  472. }
  473. /* ------------------------------------------------------------------------- */
  474. class ConnectionParameters {
  475. const DEFAULT_HOST = '127.0.0.1';
  476. const DEFAULT_PORT = 6379;
  477. const DEFAULT_TIMEOUT = 5;
  478. private $_parameters;
  479. public function __construct($parameters) {
  480. $parameters = $parameters ?: array();
  481. $this->_parameters = is_array($parameters)
  482. ? self::filterConnectionParams($parameters)
  483. : self::parseURI($parameters);
  484. }
  485. private static function parseURI($uri) {
  486. $parsed = @parse_url($uri);
  487. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  488. throw new ClientException("Invalid URI: $uri");
  489. }
  490. if (array_key_exists('query', $parsed)) {
  491. $details = array();
  492. foreach (explode('&', $parsed['query']) as $kv) {
  493. list($k, $v) = explode('=', $kv);
  494. switch ($k) {
  495. case 'database':
  496. $details['database'] = $v;
  497. break;
  498. case 'password':
  499. $details['password'] = $v;
  500. break;
  501. case 'connection_timeout':
  502. $details['connection_timeout'] = $v;
  503. break;
  504. case 'read_write_timeout':
  505. $details['read_write_timeout'] = $v;
  506. break;
  507. case 'alias':
  508. $details['alias'] = $v;
  509. break;
  510. }
  511. }
  512. $parsed = array_merge($parsed, $details);
  513. }
  514. return self::filterConnectionParams($parsed);
  515. }
  516. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  517. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  518. }
  519. private static function filterConnectionParams($parameters) {
  520. return array(
  521. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  522. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  523. 'database' => self::getParamOrDefault($parameters, 'database'),
  524. 'password' => self::getParamOrDefault($parameters, 'password'),
  525. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  526. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  527. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  528. );
  529. }
  530. public function __get($parameter) {
  531. return $this->_parameters[$parameter];
  532. }
  533. public function __isset($parameter) {
  534. return isset($this->_parameters[$parameter]);
  535. }
  536. }
  537. interface IConnection {
  538. public function connect();
  539. public function disconnect();
  540. public function isConnected();
  541. public function writeCommand(Command $command);
  542. public function readResponse(Command $command);
  543. }
  544. class Connection implements IConnection {
  545. private $_params, $_socket, $_initCmds, $_reader;
  546. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  547. $this->_params = $parameters;
  548. $this->_initCmds = array();
  549. $this->_reader = $reader ?: new ResponseReader();
  550. }
  551. public function __destruct() {
  552. $this->disconnect();
  553. }
  554. public function isConnected() {
  555. return is_resource($this->_socket);
  556. }
  557. public function connect() {
  558. if ($this->isConnected()) {
  559. throw new ClientException('Connection already estabilished');
  560. }
  561. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  562. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  563. if (!$this->_socket) {
  564. throw new ClientException(trim($errstr), $errno);
  565. }
  566. if (isset($this->_params->read_write_timeout)) {
  567. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  568. }
  569. if (count($this->_initCmds) > 0){
  570. $this->sendInitializationCommands();
  571. }
  572. }
  573. public function disconnect() {
  574. if ($this->isConnected()) {
  575. fclose($this->_socket);
  576. }
  577. }
  578. public function pushInitCommand(Command $command){
  579. $this->_initCmds[] = $command;
  580. }
  581. private function sendInitializationCommands() {
  582. foreach ($this->_initCmds as $command) {
  583. $this->writeCommand($command);
  584. }
  585. foreach ($this->_initCmds as $command) {
  586. $this->readResponse($command);
  587. }
  588. }
  589. public function writeCommand(Command $command) {
  590. $written = fwrite($this->getSocket(), $command());
  591. if ($written === false){
  592. throw new ClientException(sprintf(
  593. 'An error has occurred while writing command %s on the network stream'),
  594. $command->getCommandId()
  595. );
  596. }
  597. }
  598. public function readResponse(Command $command) {
  599. $response = $this->_reader->read($this->getSocket());
  600. return isset($response->queued) ? $response : $command->parseResponse($response);
  601. }
  602. public function rawCommand($rawCommandData, $closesConnection = false) {
  603. $socket = $this->getSocket();
  604. $written = fwrite($socket, $rawCommandData);
  605. if ($written === false){
  606. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  607. }
  608. if ($closesConnection) {
  609. return;
  610. }
  611. return $this->_reader->read($socket);
  612. }
  613. public function getSocket() {
  614. if (!$this->isConnected()) {
  615. $this->connect();
  616. }
  617. return $this->_socket;
  618. }
  619. public function getAlias() {
  620. return $this->_params->alias;
  621. }
  622. public function __toString() {
  623. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  624. }
  625. }
  626. class ConnectionCluster implements IConnection, \IteratorAggregate {
  627. // TODO: find a clean way to handle connection failures of single nodes.
  628. private $_pool, $_ring;
  629. public function __construct() {
  630. $this->_pool = array();
  631. $this->_ring = new Utilities\HashRing();
  632. }
  633. public function __destruct() {
  634. $this->disconnect();
  635. }
  636. public function isConnected() {
  637. foreach ($this->_pool as $connection) {
  638. if ($connection->isConnected()) {
  639. return true;
  640. }
  641. }
  642. return false;
  643. }
  644. public function connect() {
  645. foreach ($this->_pool as $connection) {
  646. $connection->connect();
  647. }
  648. }
  649. public function disconnect() {
  650. foreach ($this->_pool as $connection) {
  651. $connection->disconnect();
  652. }
  653. }
  654. public function add(Connection $connection) {
  655. $connectionAlias = $connection->getAlias();
  656. if (isset($connectionAlias)) {
  657. $this->_pool[$connectionAlias] = $connection;
  658. }
  659. else {
  660. $this->_pool[] = $connection;
  661. }
  662. $this->_ring->add($connection);
  663. }
  664. private function getConnection(Command $command) {
  665. if ($command->canBeHashed() === false) {
  666. throw new ClientException(
  667. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  668. );
  669. }
  670. return $this->_ring->get($command->getHash());
  671. }
  672. public function getConnectionById($id = null) {
  673. return $this->_pool[$id ?: 0];
  674. }
  675. public function getIterator() {
  676. return new \ArrayIterator($this->_pool);
  677. }
  678. public function writeCommand(Command $command) {
  679. $this->getConnection($command)->writeCommand($command);
  680. }
  681. public function readResponse(Command $command) {
  682. return $this->getConnection($command)->readResponse($command);
  683. }
  684. }
  685. /* ------------------------------------------------------------------------- */
  686. abstract class RedisServerProfile {
  687. private static $_serverProfiles;
  688. private $_registeredCommands;
  689. public function __construct() {
  690. $this->_registeredCommands = $this->getSupportedCommands();
  691. }
  692. public abstract function getVersion();
  693. protected abstract function getSupportedCommands();
  694. public static function getDefault() {
  695. return self::get('default');
  696. }
  697. private static function predisServerProfiles() {
  698. return array(
  699. '1.0' => '\Predis\RedisServer_v1_0',
  700. '1.2' => '\Predis\RedisServer_v1_2',
  701. 'default' => '\Predis\RedisServer_v1_2',
  702. 'dev' => '\Predis\RedisServer_vNext',
  703. );
  704. }
  705. public static function get($version) {
  706. if (!isset(self::$_serverProfiles)) {
  707. self::$_serverProfiles = self::predisServerProfiles();
  708. }
  709. if (!isset(self::$_serverProfiles[$version])) {
  710. throw new ClientException("Unknown server profile: $version");
  711. }
  712. $profile = self::$_serverProfiles[$version];
  713. return new $profile();
  714. }
  715. public function compareWith($version, $operator = null) {
  716. // one could expect that PHP's version_compare would behave
  717. // the same way if invoked with 2 arguments or 3 arguments
  718. // with the third being NULL, but it is not like that.
  719. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  720. // we might need to revise the behavior of this method.
  721. return ($operator === null
  722. ? version_compare($this, $version)
  723. : version_compare($this, $version, $operator)
  724. );
  725. }
  726. public function supportsCommand($command) {
  727. return isset($this->_registeredCommands[$command]);
  728. }
  729. public function createCommand($method, $arguments = array()) {
  730. if (!isset($this->_registeredCommands[$method])) {
  731. throw new ClientException("'$method' is not a registered Redis command");
  732. }
  733. $commandClass = $this->_registeredCommands[$method];
  734. $command = new $commandClass();
  735. $command->setArgumentsArray($arguments);
  736. return $command;
  737. }
  738. public function registerCommands(Array $commands) {
  739. foreach ($commands as $command => $aliases) {
  740. $this->registerCommand($command, $aliases);
  741. }
  742. }
  743. public function registerCommand($command, $aliases) {
  744. $commandReflection = new \ReflectionClass($command);
  745. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  746. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  747. }
  748. if (is_array($aliases)) {
  749. foreach ($aliases as $alias) {
  750. $this->_registeredCommands[$alias] = $command;
  751. }
  752. }
  753. else {
  754. $this->_registeredCommands[$aliases] = $command;
  755. }
  756. }
  757. public function __toString() {
  758. return $this->getVersion();
  759. }
  760. }
  761. class RedisServer_v1_0 extends RedisServerProfile {
  762. public function getVersion() { return '1.0'; }
  763. public function getSupportedCommands() {
  764. return array(
  765. /* miscellaneous commands */
  766. 'ping' => '\Predis\Commands\Ping',
  767. 'echo' => '\Predis\Commands\DoEcho',
  768. 'auth' => '\Predis\Commands\Auth',
  769. /* connection handling */
  770. 'quit' => '\Predis\Commands\Quit',
  771. /* commands operating on string values */
  772. 'set' => '\Predis\Commands\Set',
  773. 'setnx' => '\Predis\Commands\SetPreserve',
  774. 'setPreserve' => '\Predis\Commands\SetPreserve',
  775. 'get' => '\Predis\Commands\Get',
  776. 'mget' => '\Predis\Commands\GetMultiple',
  777. 'getMultiple' => '\Predis\Commands\GetMultiple',
  778. 'getset' => '\Predis\Commands\GetSet',
  779. 'getSet' => '\Predis\Commands\GetSet',
  780. 'incr' => '\Predis\Commands\Increment',
  781. 'increment' => '\Predis\Commands\Increment',
  782. 'incrby' => '\Predis\Commands\IncrementBy',
  783. 'incrementBy' => '\Predis\Commands\IncrementBy',
  784. 'decr' => '\Predis\Commands\Decrement',
  785. 'decrement' => '\Predis\Commands\Decrement',
  786. 'decrby' => '\Predis\Commands\DecrementBy',
  787. 'decrementBy' => '\Predis\Commands\DecrementBy',
  788. 'exists' => '\Predis\Commands\Exists',
  789. 'del' => '\Predis\Commands\Delete',
  790. 'delete' => '\Predis\Commands\Delete',
  791. 'type' => '\Predis\Commands\Type',
  792. /* commands operating on the key space */
  793. 'keys' => '\Predis\Commands\Keys',
  794. 'randomkey' => '\Predis\Commands\RandomKey',
  795. 'randomKey' => '\Predis\Commands\RandomKey',
  796. 'rename' => '\Predis\Commands\Rename',
  797. 'renamenx' => '\Predis\Commands\RenamePreserve',
  798. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  799. 'expire' => '\Predis\Commands\Expire',
  800. 'expireat' => '\Predis\Commands\ExpireAt',
  801. 'expireAt' => '\Predis\Commands\ExpireAt',
  802. 'dbsize' => '\Predis\Commands\DatabaseSize',
  803. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  804. 'ttl' => '\Predis\Commands\TimeToLive',
  805. 'timeToLive' => '\Predis\Commands\TimeToLive',
  806. /* commands operating on lists */
  807. 'rpush' => '\Predis\Commands\ListPushTail',
  808. 'pushTail' => '\Predis\Commands\ListPushTail',
  809. 'lpush' => '\Predis\Commands\ListPushHead',
  810. 'pushHead' => '\Predis\Commands\ListPushHead',
  811. 'llen' => '\Predis\Commands\ListLength',
  812. 'listLength' => '\Predis\Commands\ListLength',
  813. 'lrange' => '\Predis\Commands\ListRange',
  814. 'listRange' => '\Predis\Commands\ListRange',
  815. 'ltrim' => '\Predis\Commands\ListTrim',
  816. 'listTrim' => '\Predis\Commands\ListTrim',
  817. 'lindex' => '\Predis\Commands\ListIndex',
  818. 'listIndex' => '\Predis\Commands\ListIndex',
  819. 'lset' => '\Predis\Commands\ListSet',
  820. 'listSet' => '\Predis\Commands\ListSet',
  821. 'lrem' => '\Predis\Commands\ListRemove',
  822. 'listRemove' => '\Predis\Commands\ListRemove',
  823. 'lpop' => '\Predis\Commands\ListPopFirst',
  824. 'popFirst' => '\Predis\Commands\ListPopFirst',
  825. 'rpop' => '\Predis\Commands\ListPopLast',
  826. 'popLast' => '\Predis\Commands\ListPopLast',
  827. /* commands operating on sets */
  828. 'sadd' => '\Predis\Commands\SetAdd',
  829. 'setAdd' => '\Predis\Commands\SetAdd',
  830. 'srem' => '\Predis\Commands\SetRemove',
  831. 'setRemove' => '\Predis\Commands\SetRemove',
  832. 'spop' => '\Predis\Commands\SetPop',
  833. 'setPop' => '\Predis\Commands\SetPop',
  834. 'smove' => '\Predis\Commands\SetMove',
  835. 'setMove' => '\Predis\Commands\SetMove',
  836. 'scard' => '\Predis\Commands\SetCardinality',
  837. 'setCardinality' => '\Predis\Commands\SetCardinality',
  838. 'sismember' => '\Predis\Commands\SetIsMember',
  839. 'setIsMember' => '\Predis\Commands\SetIsMember',
  840. 'sinter' => '\Predis\Commands\SetIntersection',
  841. 'setIntersection' => '\Predis\Commands\SetIntersection',
  842. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  843. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  844. 'sunion' => '\Predis\Commands\SetUnion',
  845. 'setUnion' => '\Predis\Commands\SetUnion',
  846. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  847. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  848. 'sdiff' => '\Predis\Commands\SetDifference',
  849. 'setDifference' => '\Predis\Commands\SetDifference',
  850. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  851. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  852. 'smembers' => '\Predis\Commands\SetMembers',
  853. 'setMembers' => '\Predis\Commands\SetMembers',
  854. 'srandmember' => '\Predis\Commands\SetRandomMember',
  855. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  856. /* multiple databases handling commands */
  857. 'select' => '\Predis\Commands\SelectDatabase',
  858. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  859. 'move' => '\Predis\Commands\MoveKey',
  860. 'moveKey' => '\Predis\Commands\MoveKey',
  861. 'flushdb' => '\Predis\Commands\FlushDatabase',
  862. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  863. 'flushall' => '\Predis\Commands\FlushAll',
  864. 'flushDatabases' => '\Predis\Commands\FlushAll',
  865. /* sorting */
  866. 'sort' => '\Predis\Commands\Sort',
  867. /* remote server control commands */
  868. 'info' => '\Predis\Commands\Info',
  869. 'slaveof' => '\Predis\Commands\SlaveOf',
  870. 'slaveOf' => '\Predis\Commands\SlaveOf',
  871. /* persistence control commands */
  872. 'save' => '\Predis\Commands\Save',
  873. 'bgsave' => '\Predis\Commands\BackgroundSave',
  874. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  875. 'lastsave' => '\Predis\Commands\LastSave',
  876. 'lastSave' => '\Predis\Commands\LastSave',
  877. 'shutdown' => '\Predis\Commands\Shutdown',
  878. );
  879. }
  880. }
  881. class RedisServer_v1_2 extends RedisServer_v1_0 {
  882. public function getVersion() { return '1.2'; }
  883. public function getSupportedCommands() {
  884. return array_merge(parent::getSupportedCommands(), array(
  885. /* commands operating on string values */
  886. 'mset' => '\Predis\Commands\SetMultiple',
  887. 'setMultiple' => '\Predis\Commands\SetMultiple',
  888. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  889. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  890. /* commands operating on lists */
  891. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  892. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  893. /* commands operating on sorted sets */
  894. 'zadd' => '\Predis\Commands\ZSetAdd',
  895. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  896. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  897. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  898. 'zrem' => '\Predis\Commands\ZSetRemove',
  899. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  900. 'zrange' => '\Predis\Commands\ZSetRange',
  901. 'zsetRange' => '\Predis\Commands\ZSetRange',
  902. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  903. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  904. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  905. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  906. 'zcard' => '\Predis\Commands\ZSetCardinality',
  907. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  908. 'zscore' => '\Predis\Commands\ZSetScore',
  909. 'zsetScore' => '\Predis\Commands\ZSetScore',
  910. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  911. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  912. /* persistence control commands */
  913. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  914. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  915. ));
  916. }
  917. }
  918. class RedisServer_vNext extends RedisServer_v1_2 {
  919. public function getVersion() { return '1.3'; }
  920. public function getSupportedCommands() {
  921. return array_merge(parent::getSupportedCommands(), array(
  922. /* miscellaneous commands */
  923. 'multi' => '\Predis\Commands\Multi',
  924. 'exec' => '\Predis\Commands\Exec',
  925. 'append' => '\Predis\Commands\Append',
  926. /* commands operating on lists */
  927. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  928. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  929. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  930. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  931. /* commands operating on sorted sets */
  932. 'zcount' => '\Predis\Commands\ZCount',
  933. 'zsetCount' => '\Predis\Commands\ZCount',
  934. ));
  935. }
  936. }
  937. /* ------------------------------------------------------------------------- */
  938. namespace Predis\Utilities;
  939. class HashRing {
  940. const DEFAULT_REPLICAS = 128;
  941. private $_ring, $_ringKeys, $_replicas;
  942. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  943. $this->_replicas = $replicas;
  944. $this->_ring = array();
  945. $this->_ringKeys = array();
  946. }
  947. public function add($node) {
  948. $nodeHash = (string) $node;
  949. $replicas = $this->_replicas;
  950. for ($i = 0; $i < $replicas; $i++) {
  951. $key = crc32($nodeHash . ':' . $i);
  952. $this->_ring[$key] = $node;
  953. }
  954. ksort($this->_ring, SORT_NUMERIC);
  955. $this->_ringKeys = array_keys($this->_ring);
  956. }
  957. public function remove($node) {
  958. $nodeHash = (string) $node;
  959. $replicas = $this->_replicas;
  960. for ($i = 0; $i < $replicas; $i++) {
  961. $key = crc32($nodeHash . ':' . $i);
  962. unset($this->_ring[$key]);
  963. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  964. return $rk !== $key;
  965. });
  966. }
  967. }
  968. public function get($key) {
  969. return $this->_ring[$this->getNodeKey($key)];
  970. }
  971. private function getNodeKey($key) {
  972. $ringKeys = $this->_ringKeys;
  973. $upper = count($ringKeys) - 1;
  974. $lower = 0;
  975. $index = 0;
  976. while ($lower <= $upper) {
  977. $index = ($lower + $upper) / 2;
  978. $item = $ringKeys[$index];
  979. if ($item > $key) {
  980. $upper = $index - 1;
  981. }
  982. else if ($item < $key) {
  983. $lower = $index + 1;
  984. }
  985. else {
  986. return $index;
  987. }
  988. }
  989. return $ringKeys[$upper];
  990. }
  991. }
  992. /* ------------------------------------------------------------------------- */
  993. namespace Predis\Commands;
  994. /* miscellaneous commands */
  995. class Ping extends \Predis\InlineCommand {
  996. public function canBeHashed() { return false; }
  997. public function getCommandId() { return 'PING'; }
  998. public function parseResponse($data) {
  999. return $data === 'PONG' ? true : false;
  1000. }
  1001. }
  1002. class DoEcho extends \Predis\BulkCommand {
  1003. public function canBeHashed() { return false; }
  1004. public function getCommandId() { return 'ECHO'; }
  1005. }
  1006. class Auth extends \Predis\InlineCommand {
  1007. public function canBeHashed() { return false; }
  1008. public function getCommandId() { return 'AUTH'; }
  1009. }
  1010. /* connection handling */
  1011. class Quit extends \Predis\InlineCommand {
  1012. public function canBeHashed() { return false; }
  1013. public function getCommandId() { return 'QUIT'; }
  1014. public function closesConnection() { return true; }
  1015. }
  1016. /* commands operating on string values */
  1017. class Set extends \Predis\BulkCommand {
  1018. public function getCommandId() { return 'SET'; }
  1019. }
  1020. class SetPreserve extends \Predis\BulkCommand {
  1021. public function getCommandId() { return 'SETNX'; }
  1022. public function parseResponse($data) { return (bool) $data; }
  1023. }
  1024. class SetMultiple extends \Predis\MultiBulkCommand {
  1025. public function canBeHashed() { return false; }
  1026. public function getCommandId() { return 'MSET'; }
  1027. }
  1028. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1029. public function canBeHashed() { return false; }
  1030. public function getCommandId() { return 'MSETNX'; }
  1031. public function parseResponse($data) { return (bool) $data; }
  1032. }
  1033. class Get extends \Predis\InlineCommand {
  1034. public function getCommandId() { return 'GET'; }
  1035. }
  1036. class GetMultiple extends \Predis\InlineCommand {
  1037. public function canBeHashed() { return false; }
  1038. public function getCommandId() { return 'MGET'; }
  1039. }
  1040. class GetSet extends \Predis\BulkCommand {
  1041. public function getCommandId() { return 'GETSET'; }
  1042. }
  1043. class Increment extends \Predis\InlineCommand {
  1044. public function getCommandId() { return 'INCR'; }
  1045. }
  1046. class IncrementBy extends \Predis\InlineCommand {
  1047. public function getCommandId() { return 'INCRBY'; }
  1048. }
  1049. class Decrement extends \Predis\InlineCommand {
  1050. public function getCommandId() { return 'DECR'; }
  1051. }
  1052. class DecrementBy extends \Predis\InlineCommand {
  1053. public function getCommandId() { return 'DECRBY'; }
  1054. }
  1055. class Exists extends \Predis\InlineCommand {
  1056. public function getCommandId() { return 'EXISTS'; }
  1057. public function parseResponse($data) { return (bool) $data; }
  1058. }
  1059. class Delete extends \Predis\InlineCommand {
  1060. public function getCommandId() { return 'DEL'; }
  1061. public function parseResponse($data) { return (bool) $data; }
  1062. }
  1063. class Type extends \Predis\InlineCommand {
  1064. public function getCommandId() { return 'TYPE'; }
  1065. }
  1066. /* commands operating on the key space */
  1067. class Keys extends \Predis\InlineCommand {
  1068. public function canBeHashed() { return false; }
  1069. public function getCommandId() { return 'KEYS'; }
  1070. public function parseResponse($data) {
  1071. // TODO: is this behaviour correct?
  1072. return strlen($data) > 0 ? explode(' ', $data) : array();
  1073. }
  1074. }
  1075. class RandomKey extends \Predis\InlineCommand {
  1076. public function canBeHashed() { return false; }
  1077. public function getCommandId() { return 'RANDOMKEY'; }
  1078. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1079. }
  1080. class Rename extends \Predis\InlineCommand {
  1081. public function canBeHashed() { return false; }
  1082. public function getCommandId() { return 'RENAME'; }
  1083. }
  1084. class RenamePreserve extends \Predis\InlineCommand {
  1085. public function canBeHashed() { return false; }
  1086. public function getCommandId() { return 'RENAMENX'; }
  1087. public function parseResponse($data) { return (bool) $data; }
  1088. }
  1089. class Expire extends \Predis\InlineCommand {
  1090. public function getCommandId() { return 'EXPIRE'; }
  1091. public function parseResponse($data) { return (bool) $data; }
  1092. }
  1093. class ExpireAt extends \Predis\InlineCommand {
  1094. public function getCommandId() { return 'EXPIREAT'; }
  1095. public function parseResponse($data) { return (bool) $data; }
  1096. }
  1097. class DatabaseSize extends \Predis\InlineCommand {
  1098. public function canBeHashed() { return false; }
  1099. public function getCommandId() { return 'DBSIZE'; }
  1100. }
  1101. class TimeToLive extends \Predis\InlineCommand {
  1102. public function getCommandId() { return 'TTL'; }
  1103. }
  1104. /* commands operating on lists */
  1105. class ListPushTail extends \Predis\BulkCommand {
  1106. public function getCommandId() { return 'RPUSH'; }
  1107. }
  1108. class ListPushHead extends \Predis\BulkCommand {
  1109. public function getCommandId() { return 'LPUSH'; }
  1110. }
  1111. class ListLength extends \Predis\InlineCommand {
  1112. public function getCommandId() { return 'LLEN'; }
  1113. }
  1114. class ListRange extends \Predis\InlineCommand {
  1115. public function getCommandId() { return 'LRANGE'; }
  1116. }
  1117. class ListTrim extends \Predis\InlineCommand {
  1118. public function getCommandId() { return 'LTRIM'; }
  1119. }
  1120. class ListIndex extends \Predis\InlineCommand {
  1121. public function getCommandId() { return 'LINDEX'; }
  1122. }
  1123. class ListSet extends \Predis\BulkCommand {
  1124. public function getCommandId() { return 'LSET'; }
  1125. }
  1126. class ListRemove extends \Predis\BulkCommand {
  1127. public function getCommandId() { return 'LREM'; }
  1128. }
  1129. class ListPopLastPushHead extends \Predis\InlineCommand {
  1130. public function getCommandId() { return 'RPOPLPUSH'; }
  1131. }
  1132. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1133. public function getCommandId() { return 'RPOPLPUSH'; }
  1134. }
  1135. class ListPopFirst extends \Predis\InlineCommand {
  1136. public function getCommandId() { return 'LPOP'; }
  1137. }
  1138. class ListPopLast extends \Predis\InlineCommand {
  1139. public function getCommandId() { return 'RPOP'; }
  1140. }
  1141. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1142. public function getCommandId() { return 'BLPOP'; }
  1143. }
  1144. class ListPopLastBlocking extends \Predis\InlineCommand {
  1145. public function getCommandId() { return 'BRPOP'; }
  1146. }
  1147. /* commands operating on sets */
  1148. class SetAdd extends \Predis\BulkCommand {
  1149. public function getCommandId() { return 'SADD'; }
  1150. public function parseResponse($data) { return (bool) $data; }
  1151. }
  1152. class SetRemove extends \Predis\BulkCommand {
  1153. public function getCommandId() { return 'SREM'; }
  1154. public function parseResponse($data) { return (bool) $data; }
  1155. }
  1156. class SetPop extends \Predis\InlineCommand {
  1157. public function getCommandId() { return 'SPOP'; }
  1158. }
  1159. class SetMove extends \Predis\BulkCommand {
  1160. public function canBeHashed() { return false; }
  1161. public function getCommandId() { return 'SMOVE'; }
  1162. public function parseResponse($data) { return (bool) $data; }
  1163. }
  1164. class SetCardinality extends \Predis\InlineCommand {
  1165. public function getCommandId() { return 'SCARD'; }
  1166. }
  1167. class SetIsMember extends \Predis\BulkCommand {
  1168. public function getCommandId() { return 'SISMEMBER'; }
  1169. public function parseResponse($data) { return (bool) $data; }
  1170. }
  1171. class SetIntersection extends \Predis\InlineCommand {
  1172. public function getCommandId() { return 'SINTER'; }
  1173. }
  1174. class SetIntersectionStore extends \Predis\InlineCommand {
  1175. public function getCommandId() { return 'SINTERSTORE'; }
  1176. }
  1177. class SetUnion extends \Predis\InlineCommand {
  1178. public function getCommandId() { return 'SUNION'; }
  1179. }
  1180. class SetUnionStore extends \Predis\InlineCommand {
  1181. public function getCommandId() { return 'SUNIONSTORE'; }
  1182. }
  1183. class SetDifference extends \Predis\InlineCommand {
  1184. public function getCommandId() { return 'SDIFF'; }
  1185. }
  1186. class SetDifferenceStore extends \Predis\InlineCommand {
  1187. public function getCommandId() { return 'SDIFFSTORE'; }
  1188. }
  1189. class SetMembers extends \Predis\InlineCommand {
  1190. public function getCommandId() { return 'SMEMBERS'; }
  1191. }
  1192. class SetRandomMember extends \Predis\InlineCommand {
  1193. public function getCommandId() { return 'SRANDMEMBER'; }
  1194. }
  1195. /* commands operating on sorted sets */
  1196. class ZSetAdd extends \Predis\BulkCommand {
  1197. public function getCommandId() { return 'ZADD'; }
  1198. public function parseResponse($data) { return (bool) $data; }
  1199. }
  1200. class ZSetIncrementBy extends \Predis\BulkCommand {
  1201. public function getCommandId() { return 'ZINCRBY'; }
  1202. }
  1203. class ZSetRemove extends \Predis\BulkCommand {
  1204. public function getCommandId() { return 'ZREM'; }
  1205. public function parseResponse($data) { return (bool) $data; }
  1206. }
  1207. class ZSetRange extends \Predis\InlineCommand {
  1208. public function getCommandId() { return 'ZRANGE'; }
  1209. public function parseResponse($data) {
  1210. $arguments = $this->getArguments();
  1211. if (count($arguments) === 4) {
  1212. if (strtolower($arguments[3]) === 'withscores') {
  1213. $result = array();
  1214. for ($i = 0; $i < count($data); $i++) {
  1215. $result[] = array($data[$i], $data[++$i]);
  1216. }
  1217. return $result;
  1218. }
  1219. }
  1220. return $data;
  1221. }
  1222. }
  1223. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1224. public function getCommandId() { return 'ZREVRANGE'; }
  1225. }
  1226. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1227. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1228. }
  1229. class ZCount extends \Predis\InlineCommand {
  1230. public function getCommandId() { return 'ZCOUNT'; }
  1231. }
  1232. class ZSetCardinality extends \Predis\InlineCommand {
  1233. public function getCommandId() { return 'ZCARD'; }
  1234. }
  1235. class ZSetScore extends \Predis\BulkCommand {
  1236. public function getCommandId() { return 'ZSCORE'; }
  1237. }
  1238. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1239. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1240. }
  1241. /* multiple databases handling commands */
  1242. class SelectDatabase extends \Predis\InlineCommand {
  1243. public function canBeHashed() { return false; }
  1244. public function getCommandId() { return 'SELECT'; }
  1245. }
  1246. class MoveKey extends \Predis\InlineCommand {
  1247. public function canBeHashed() { return false; }
  1248. public function getCommandId() { return 'MOVE'; }
  1249. public function parseResponse($data) { return (bool) $data; }
  1250. }
  1251. class FlushDatabase extends \Predis\InlineCommand {
  1252. public function canBeHashed() { return false; }
  1253. public function getCommandId() { return 'FLUSHDB'; }
  1254. }
  1255. class FlushAll extends \Predis\InlineCommand {
  1256. public function canBeHashed() { return false; }
  1257. public function getCommandId() { return 'FLUSHALL'; }
  1258. }
  1259. /* sorting */
  1260. class Sort extends \Predis\InlineCommand {
  1261. public function getCommandId() { return 'SORT'; }
  1262. public function filterArguments(Array $arguments) {
  1263. if (count($arguments) === 1) {
  1264. return $arguments;
  1265. }
  1266. // TODO: add more parameters checks
  1267. $query = array($arguments[0]);
  1268. $sortParams = $arguments[1];
  1269. if (isset($sortParams['by'])) {
  1270. $query[] = 'BY ' . $sortParams['by'];
  1271. }
  1272. if (isset($sortParams['get'])) {
  1273. $getargs = $sortParams['get'];
  1274. if (is_array($getargs)) {
  1275. foreach ($getargs as $getarg) {
  1276. $query[] = 'GET ' . $getarg;
  1277. }
  1278. }
  1279. else {
  1280. $query[] = 'GET ' . $getargs;
  1281. }
  1282. }
  1283. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1284. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1285. }
  1286. if (isset($sortParams['sort'])) {
  1287. $query[] = strtoupper($sortParams['sort']);
  1288. }
  1289. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1290. $query[] = 'ALPHA';
  1291. }
  1292. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1293. $query[] = 'STORE ' . $sortParams['store'];
  1294. }
  1295. return $query;
  1296. }
  1297. }
  1298. /* persistence control commands */
  1299. class Save extends \Predis\InlineCommand {
  1300. public function canBeHashed() { return false; }
  1301. public function getCommandId() { return 'SAVE'; }
  1302. }
  1303. class BackgroundSave extends \Predis\InlineCommand {
  1304. public function canBeHashed() { return false; }
  1305. public function getCommandId() { return 'BGSAVE'; }
  1306. public function parseResponse($data) {
  1307. if ($data == 'Background saving started') {
  1308. return true;
  1309. }
  1310. return $data;
  1311. }
  1312. }
  1313. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1314. public function canBeHashed() { return false; }
  1315. public function getCommandId() { return 'BGREWRITEAOF'; }
  1316. public function parseResponse($data) {
  1317. return $data == 'Background append only file rewriting started';
  1318. }
  1319. }
  1320. class LastSave extends \Predis\InlineCommand {
  1321. public function canBeHashed() { return false; }
  1322. public function getCommandId() { return 'LASTSAVE'; }
  1323. }
  1324. class Shutdown extends \Predis\InlineCommand {
  1325. public function canBeHashed() { return false; }
  1326. public function getCommandId() { return 'SHUTDOWN'; }
  1327. public function closesConnection() { return true; }
  1328. }
  1329. /* remote server control commands */
  1330. class Info extends \Predis\InlineCommand {
  1331. public function canBeHashed() { return false; }
  1332. public function getCommandId() { return 'INFO'; }
  1333. public function parseResponse($data) {
  1334. $info = array();
  1335. $infoLines = explode("\r\n", $data, -1);
  1336. foreach ($infoLines as $row) {
  1337. list($k, $v) = explode(':', $row);
  1338. if (!preg_match('/^db\d+$/', $k)) {
  1339. $info[$k] = $v;
  1340. }
  1341. else {
  1342. $db = array();
  1343. foreach (explode(',', $v) as $dbvar) {
  1344. list($dbvk, $dbvv) = explode('=', $dbvar);
  1345. $db[trim($dbvk)] = $dbvv;
  1346. }
  1347. $info[$k] = $db;
  1348. }
  1349. }
  1350. return $info;
  1351. }
  1352. }
  1353. class SlaveOf extends \Predis\InlineCommand {
  1354. public function canBeHashed() { return false; }
  1355. public function getCommandId() { return 'SLAVEOF'; }
  1356. public function filterArguments(Array $arguments) {
  1357. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1358. }
  1359. }
  1360. class Multi extends \Predis\InlineCommand {
  1361. public function canBeHashed() { return false; }
  1362. public function getCommandId() { return 'MULTI'; }
  1363. }
  1364. class Exec extends \Predis\InlineCommand {
  1365. public function canBeHashed() { return false; }
  1366. public function getCommandId() { return 'EXEC'; }
  1367. }
  1368. class Append extends \Predis\BulkCommand {
  1369. public function getCommandId() { return 'APPEND'; }
  1370. }
  1371. ?>