Config.php 2.3 KB

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