]> _ Git - cubist_util.git/commitdiff
wip #6693 @0.25
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 30 Jan 2024 07:38:57 +0000 (08:38 +0100)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Tue, 30 Jan 2024 07:38:57 +0000 (08:38 +0100)
src/Env.php

index 5a919be110d4790bc61997211c0760aa686468c8..2d1bf30fe3e06de874045aad6c57a398092033eb 100644 (file)
@@ -18,4 +18,33 @@ class Env
         }
         return $f;
     }
+
+    /**
+     * @param $filePath string
+     * @param $array array
+     * @return void
+     * @see https://www.faqforge.com/php/how-to-write-an-array-to-an-env-file-using-php/
+     */
+    public static function arrayToEnvFile($filePath, $array)
+    {
+        $content = '';
+
+        foreach ($array as $key => $value) {
+            // Ensure the key is a string and the value is scalar (not an array, object, etc.)
+            if (!is_string($key) || !is_scalar($value)) {
+                throw new InvalidArgumentException("Invalid key or value type.");
+            }
+
+            // Escape if needed and format the line
+            $key = strtoupper($key); // Optional: convert keys to uppercase
+            $value = strval($value); // Convert the value to a string
+            $value = strpos($value, ' ') !== false ? '"' . $value . '"' : $value; // Enclose the value in quotes if it contains spaces
+            $content .= "{$key}={$value}\n";
+        }
+
+        // Write to file
+        if (file_put_contents($filePath, $content) === false) {
+            throw new RuntimeException("Failed to write to the file at $filePath.");
+        }
+    }
 }
\ No newline at end of file