diff --git a/Config.php b/Config.php index a3978e6bbad618c060ee0b8e7a80bb8ead6f3519..2125b052f16fcbc49237470cd4bae84304649d0b 100644 --- a/Config.php +++ b/Config.php @@ -31,6 +31,16 @@ final class Config { */ private $twig; + /** + * @var \LakeDrops\Component\Composer\Dotenv + */ + private $env; + + /** + * @var string + */ + private $configFile; + /** * Config constructor. * @@ -40,12 +50,14 @@ final class Config { */ public function __construct(string $component, array $default_values, Dotenv $env) { $this->component = $component; + $this->env = $env; $this->twig_loader = new Twig_Loader_Array([]); $this->twig = new Twig_Environment($this->twig_loader); + $this->configFile = getcwd() . '/.project.yaml'; $this->init(); $componentValues = self::$values[$component] ?? []; - self::$values[$component] = $env->replaceEnvironmentVariables(NestedArray::mergeDeep($default_values, $componentValues)); + $this->merge($default_values, $componentValues); } /** @@ -53,14 +65,31 @@ final class Config { */ private function init(): void { if (self::$values === NULL) { - $configFile = getcwd() . '/.project.yaml'; - if (!file_exists($configFile)) { - file_put_contents($configFile, Yaml::dump([], 9, 2)); + if (!file_exists($this->configFile)) { + self::$values = []; + $this->save(); + } + else { + self::$values = Yaml::parseFile($this->configFile); } - self::$values = Yaml::parseFile($configFile); } } + /** + * @param array $values1 + * @param array $values2 + */ + private function merge(array $values1, array $values2): void { + self::$values[$this->component] = $this->env->replaceEnvironmentVariables(NestedArray::mergeDeep($values1, $values2)); + } + + /** + * Save the current settings. + */ + private function save(): void { + file_put_contents($this->configFile, Yaml::dump(self::$values, 9, 2)); + } + /** * @param array $values * @param array $keys @@ -76,7 +105,6 @@ final class Config { return $values[$key]; } return $this->readValueFromArray($values[$key], $keys); - } /** @@ -89,6 +117,14 @@ final class Config { return $this->readValueFromArray(self::$values[$this->component], $parts); } + /** + * @param array $values + */ + public function setValue(array $values): void { + $this->merge(self::$values[$this->component], [$this->component => $values]); + $this->save(); + } + /** * @param string $filename * @param string $content