Skip to content

Added method for processing JSON file to environment variables. #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 46 additions & 4 deletions src/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
class Environment
{

protected static array $cache = [];

/**
* The currently supported environment classes.
*/
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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);
}
}
}
}