Config.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\Config\ConfigSourceInterface;
  13. /**
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class Config
  17. {
  18. const RELATIVE_PATHS = 1;
  19. public static $defaultConfig = array(
  20. 'process-timeout' => 300,
  21. 'use-include-path' => false,
  22. 'preferred-install' => 'auto',
  23. 'notify-on-install' => true,
  24. 'github-protocols' => array('https', 'ssh', 'git'),
  25. 'vendor-dir' => 'vendor',
  26. 'bin-dir' => '{$vendor-dir}/bin',
  27. 'cache-dir' => '{$home}/cache',
  28. 'data-dir' => '{$home}',
  29. 'cache-files-dir' => '{$cache-dir}/files',
  30. 'cache-repo-dir' => '{$cache-dir}/repo',
  31. 'cache-vcs-dir' => '{$cache-dir}/vcs',
  32. 'cache-ttl' => 15552000, // 6 months
  33. 'cache-files-ttl' => null, // fallback to cache-ttl
  34. 'cache-files-maxsize' => '300MiB',
  35. 'bin-compat' => 'auto',
  36. 'discard-changes' => false,
  37. 'autoloader-suffix' => null,
  38. 'sort-packages' => false,
  39. 'optimize-autoloader' => false,
  40. 'classmap-authoritative' => false,
  41. 'prepend-autoloader' => true,
  42. 'github-domains' => array('github.com'),
  43. 'disable-tls' => false,
  44. 'secure-http' => true,
  45. 'cafile' => null,
  46. 'capath' => null,
  47. 'github-expose-hostname' => true,
  48. 'gitlab-domains' => array('gitlab.com'),
  49. 'store-auths' => 'prompt',
  50. 'platform' => array(),
  51. 'archive-format' => 'tar',
  52. 'archive-dir' => '.',
  53. // valid keys without defaults (auth config stuff):
  54. // github-oauth
  55. // gitlab-oauth
  56. // http-basic
  57. );
  58. public static $defaultRepositories = array(
  59. 'packagist' => array(
  60. 'type' => 'composer',
  61. 'url' => 'https?://packagist.org',
  62. 'allow_ssl_downgrade' => true,
  63. ),
  64. );
  65. private $config;
  66. private $baseDir;
  67. private $repositories;
  68. private $configSource;
  69. private $authConfigSource;
  70. private $useEnvironment;
  71. /**
  72. * @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings
  73. */
  74. public function __construct($useEnvironment = true, $baseDir = null)
  75. {
  76. // load defaults
  77. $this->config = static::$defaultConfig;
  78. $this->repositories = static::$defaultRepositories;
  79. $this->useEnvironment = (bool) $useEnvironment;
  80. $this->baseDir = $baseDir;
  81. }
  82. public function setConfigSource(ConfigSourceInterface $source)
  83. {
  84. $this->configSource = $source;
  85. }
  86. public function getConfigSource()
  87. {
  88. return $this->configSource;
  89. }
  90. public function setAuthConfigSource(ConfigSourceInterface $source)
  91. {
  92. $this->authConfigSource = $source;
  93. }
  94. public function getAuthConfigSource()
  95. {
  96. return $this->authConfigSource;
  97. }
  98. /**
  99. * Merges new config values with the existing ones (overriding)
  100. *
  101. * @param array $config
  102. */
  103. public function merge($config)
  104. {
  105. // override defaults with given config
  106. if (!empty($config['config']) && is_array($config['config'])) {
  107. foreach ($config['config'] as $key => $val) {
  108. if (in_array($key, array('github-oauth', 'gitlab-oauth', 'http-basic')) && isset($this->config[$key])) {
  109. $this->config[$key] = array_merge($this->config[$key], $val);
  110. } elseif ('preferred-install' === $key && isset($this->config[$key])) {
  111. if (is_array($val) || is_array($this->config[$key])) {
  112. if (is_string($val)) {
  113. $val = array('*' => $val);
  114. }
  115. if (is_string($this->config[$key])) {
  116. $this->config[$key] = array('*' => $this->config[$key]);
  117. }
  118. $this->config[$key] = array_merge($this->config[$key], $val);
  119. // the full match pattern needs to be last
  120. if (isset($this->config[$key]['*'])) {
  121. $wildcard = $this->config[$key]['*'];
  122. unset($this->config[$key]['*']);
  123. $this->config[$key]['*'] = $wildcard;
  124. }
  125. } else {
  126. $this->config[$key] = $val;
  127. }
  128. } else {
  129. $this->config[$key] = $val;
  130. }
  131. }
  132. }
  133. if (!empty($config['repositories']) && is_array($config['repositories'])) {
  134. $this->repositories = array_reverse($this->repositories, true);
  135. $newRepos = array_reverse($config['repositories'], true);
  136. foreach ($newRepos as $name => $repository) {
  137. // disable a repository by name
  138. if (false === $repository) {
  139. unset($this->repositories[$name]);
  140. continue;
  141. }
  142. // disable a repository with an anonymous {"name": false} repo
  143. if (is_array($repository) && 1 === count($repository) && false === current($repository)) {
  144. unset($this->repositories[key($repository)]);
  145. continue;
  146. }
  147. // store repo
  148. if (is_int($name)) {
  149. $this->repositories[] = $repository;
  150. } else {
  151. $this->repositories[$name] = $repository;
  152. }
  153. }
  154. $this->repositories = array_reverse($this->repositories, true);
  155. }
  156. }
  157. /**
  158. * @return array
  159. */
  160. public function getRepositories()
  161. {
  162. return $this->repositories;
  163. }
  164. /**
  165. * Returns a setting
  166. *
  167. * @param string $key
  168. * @param int $flags Options (see class constants)
  169. * @throws \RuntimeException
  170. * @return mixed
  171. */
  172. public function get($key, $flags = 0)
  173. {
  174. switch ($key) {
  175. case 'vendor-dir':
  176. case 'bin-dir':
  177. case 'process-timeout':
  178. case 'data-dir':
  179. case 'cache-dir':
  180. case 'cache-files-dir':
  181. case 'cache-repo-dir':
  182. case 'cache-vcs-dir':
  183. case 'cafile':
  184. case 'capath':
  185. // convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
  186. $env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
  187. $val = rtrim($this->process($this->getComposerEnv($env) ?: $this->config[$key], $flags), '/\\');
  188. $val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $val);
  189. if (substr($key, -4) !== '-dir') {
  190. return $val;
  191. }
  192. return (($flags & self::RELATIVE_PATHS) == self::RELATIVE_PATHS) ? $val : $this->realpath($val);
  193. case 'cache-ttl':
  194. return (int) $this->config[$key];
  195. case 'cache-files-maxsize':
  196. if (!preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $this->config[$key], $matches)) {
  197. throw new \RuntimeException(
  198. "Could not parse the value of 'cache-files-maxsize': {$this->config[$key]}"
  199. );
  200. }
  201. $size = $matches[1];
  202. if (isset($matches[2])) {
  203. switch (strtolower($matches[2])) {
  204. case 'g':
  205. $size *= 1024;
  206. // intentional fallthrough
  207. case 'm':
  208. $size *= 1024;
  209. // intentional fallthrough
  210. case 'k':
  211. $size *= 1024;
  212. break;
  213. }
  214. }
  215. return $size;
  216. case 'cache-files-ttl':
  217. if (isset($this->config[$key])) {
  218. return (int) $this->config[$key];
  219. }
  220. return (int) $this->config['cache-ttl'];
  221. case 'home':
  222. $val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $this->config[$key]);
  223. return rtrim($this->process($val, $flags), '/\\');
  224. case 'bin-compat':
  225. $value = $this->getComposerEnv('COMPOSER_BIN_COMPAT') ?: $this->config[$key];
  226. if (!in_array($value, array('auto', 'full'))) {
  227. throw new \RuntimeException(
  228. "Invalid value for 'bin-compat': {$value}. Expected auto, full"
  229. );
  230. }
  231. return $value;
  232. case 'discard-changes':
  233. if ($env = $this->getComposerEnv('COMPOSER_DISCARD_CHANGES')) {
  234. if (!in_array($env, array('stash', 'true', 'false', '1', '0'), true)) {
  235. throw new \RuntimeException(
  236. "Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash"
  237. );
  238. }
  239. if ('stash' === $env) {
  240. return 'stash';
  241. }
  242. // convert string value to bool
  243. return $env !== 'false' && (bool) $env;
  244. }
  245. if (!in_array($this->config[$key], array(true, false, 'stash'), true)) {
  246. throw new \RuntimeException(
  247. "Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash"
  248. );
  249. }
  250. return $this->config[$key];
  251. case 'github-protocols':
  252. $protos = $this->config['github-protocols'];
  253. if ($this->config['secure-http'] && false !== ($index = array_search('git', $protos))) {
  254. unset($protos[$index]);
  255. }
  256. if (reset($protos) === 'http') {
  257. throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"');
  258. }
  259. return $protos;
  260. case 'disable-tls':
  261. return $this->config[$key] !== 'false' && (bool) $this->config[$key];
  262. case 'secure-http':
  263. return $this->config[$key] !== 'false' && (bool) $this->config[$key];
  264. default:
  265. if (!isset($this->config[$key])) {
  266. return null;
  267. }
  268. return $this->process($this->config[$key], $flags);
  269. }
  270. }
  271. public function all($flags = 0)
  272. {
  273. $all = array(
  274. 'repositories' => $this->getRepositories(),
  275. );
  276. foreach (array_keys($this->config) as $key) {
  277. $all['config'][$key] = $this->get($key, $flags);
  278. }
  279. return $all;
  280. }
  281. public function raw()
  282. {
  283. return array(
  284. 'repositories' => $this->getRepositories(),
  285. 'config' => $this->config,
  286. );
  287. }
  288. /**
  289. * Checks whether a setting exists
  290. *
  291. * @param string $key
  292. * @return bool
  293. */
  294. public function has($key)
  295. {
  296. return array_key_exists($key, $this->config);
  297. }
  298. /**
  299. * Replaces {$refs} inside a config string
  300. *
  301. * @param string $value a config string that can contain {$refs-to-other-config}
  302. * @param int $flags Options (see class constants)
  303. * @return string
  304. */
  305. private function process($value, $flags)
  306. {
  307. $config = $this;
  308. if (!is_string($value)) {
  309. return $value;
  310. }
  311. return preg_replace_callback('#\{\$(.+)\}#', function ($match) use ($config, $flags) {
  312. return $config->get($match[1], $flags);
  313. }, $value);
  314. }
  315. /**
  316. * Turns relative paths in absolute paths without realpath()
  317. *
  318. * Since the dirs might not exist yet we can not call realpath or it will fail.
  319. *
  320. * @param string $path
  321. * @return string
  322. */
  323. private function realpath($path)
  324. {
  325. if (preg_match('{^(?:/|[a-z]:|[a-z0-9.]+://)}i', $path)) {
  326. return $path;
  327. }
  328. return $this->baseDir . '/' . $path;
  329. }
  330. /**
  331. * Reads the value of a Composer environment variable
  332. *
  333. * This should be used to read COMPOSER_ environment variables
  334. * that overload config values.
  335. *
  336. * @param string $var
  337. * @return string|bool
  338. */
  339. private function getComposerEnv($var)
  340. {
  341. if ($this->useEnvironment) {
  342. return getenv($var);
  343. }
  344. return false;
  345. }
  346. }