From 59f2c0416e385e0e0c153a418e1321a336e99c4c Mon Sep 17 00:00:00 2001
From: jurgenhaas <juergen.haas@lakedrops.com>
Date: Sat, 26 Dec 2020 10:42:20 +0100
Subject: [PATCH] docker/l3d#58 Move project settings out of composer.json

---
 Config.php | 48 ++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 42 insertions(+), 6 deletions(-)

diff --git a/Config.php b/Config.php
index a3978e6..2125b05 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
-- 
GitLab