Config.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. /**
  13. * @author Jordi Boggiano <j.boggiano@seld.be>
  14. */
  15. class Config
  16. {
  17. private $config;
  18. public function __construct()
  19. {
  20. // load defaults
  21. $this->config = array(
  22. 'process-timeout' => 300,
  23. 'vendor-dir' => 'vendor',
  24. 'bin-dir' => '{$vendor-dir}/bin',
  25. 'notify-on-install' => true,
  26. );
  27. }
  28. /**
  29. * Merges new config values with the existing ones (overriding)
  30. *
  31. * @param array $config
  32. */
  33. public function merge(array $config)
  34. {
  35. // override defaults with given config
  36. if (!empty($config['config']) && is_array($config['config'])) {
  37. $this->config = array_replace_recursive($this->config, $config['config']);
  38. }
  39. }
  40. /**
  41. * Returns a setting
  42. *
  43. * @param string $key
  44. * @return mixed
  45. */
  46. public function get($key)
  47. {
  48. switch ($key) {
  49. case 'vendor-dir':
  50. case 'bin-dir':
  51. case 'process-timeout':
  52. // convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
  53. $env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
  54. return $this->process(getenv($env) ?: $this->config[$key]);
  55. case 'home':
  56. return rtrim($this->process($this->config[$key]), '/\\');
  57. default:
  58. return $this->process($this->config[$key]);
  59. }
  60. }
  61. /**
  62. * Checks whether a setting exists
  63. *
  64. * @param string $key
  65. * @return Boolean
  66. */
  67. public function has($key)
  68. {
  69. return array_key_exists($key, $this->config);
  70. }
  71. /**
  72. * Replaces {$refs} inside a config string
  73. *
  74. * @param string a config string that can contain {$refs-to-other-config}
  75. * @return string
  76. */
  77. private function process($value)
  78. {
  79. $config = $this;
  80. return preg_replace_callback('#\{\$(.+)\}#', function ($match) use ($config) {
  81. return $config->get($match[1]);
  82. }, $value);
  83. }
  84. }