From 601e15bd4f99a05a2c4be400a475d1473bb30e84 Mon Sep 17 00:00:00 2001 From: Vincent Vanwaelscappel Date: Tue, 30 Jan 2024 08:38:57 +0100 Subject: [PATCH] wip #6693 @0.25 --- src/Env.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/Env.php b/src/Env.php index 5a919be..2d1bf30 100644 --- a/src/Env.php +++ b/src/Env.php @@ -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 -- 2.39.5