From fbacb9767ef93d95bbeaf8a940d0f18824177ab7 Mon Sep 17 00:00:00 2001 From: Dave Reid Date: Thu, 17 Jul 2025 09:32:08 -0500 Subject: [PATCH] Added method for processing JSON file to environent variables. --- src/Environment.php | 50 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/src/Environment.php b/src/Environment.php index eaf291a..95e6727 100644 --- a/src/Environment.php +++ b/src/Environment.php @@ -23,6 +23,8 @@ class Environment { + protected static array $cache = []; + /** * The currently supported environment classes. */ @@ -87,11 +89,24 @@ public static function __callStatic(string $name, array $arguments) */ public static function get(string $name): string|bool { - static $cache = []; - if (!array_key_exists($name, $cache)) { - $cache[$name] = getenv($name); + if (!array_key_exists($name, static::$cache)) { + static::$cache[$name] = getenv($name); } - return $cache[$name]; + return static::$cache[$name]; + } + + /** + * Set an environment variable. + * + * @param string $name + * The name of the environment variable to set. + * @param string $value + * The value of the environment variable to set. + */ + public static function put(string $name, string $value): void + { + putenv("$name=$value"); + static::$cache[$name] = $value; } /** @@ -180,4 +195,31 @@ public static function getComposerLockFilename(): string $filename = static::getComposerFilename(); return pathinfo($filename, PATHINFO_FILENAME) . '.lock'; } + + /** + * Process a file that contains environment variables to the current environment. + * + * @param string $file + * The path to the JSON file. + */ + public static function processEnvironmentFileJson(string $file): void + { + if (is_file($file)) { + $contents = @file_get_contents($file); + if ($contents === FALSE) { + throw new \RuntimeException("Unable to read environment file $file."); + } + + $values = json_decode($contents, TRUE, 512, JSON_THROW_ON_ERROR); + + // We only support key value secrets that are strings. + $values = array_filter($values, function ($value, $key) { + return is_string($key) && is_string($value); + }, ARRAY_FILTER_USE_BOTH); + + foreach ($values as $name => $value) { + Environment::put($name, $value); + } + } + } }