You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.1 KiB
PHP

<?php
namespace Bsr\Utils;
class DotEnv {
public static function loadFromFile($filepath) {
if (!file_exists($filepath)) {
throw new \Exception("Cannot find file: $filepath");
}
$contents = file_get_contents($filepath);
$lines = explode(PHP_EOL, $contents);
$envvars = array_reduce($lines, function ($vars, $line) {
$parts = explode('=', $line);
$partsCount = count($parts);
if ($partsCount === 1 && strlen($parts[0]) <= 0) {
return $vars;
}
[$varname, $value] = $partsCount === 1
? [$parts[0], '']
: ($partsCount > 2
? [$parts[0], implode('=', array_slice($parts, 1))]
: $parts
);
$vars[$varname] = $value;
return $vars;
}, []);
return $envvars;
}
public static function MUTATE_SERVER_addEnvVars(array $variables) {
$_SERVER = array_merge($_SERVER, $variables);
}
public static function load(string $rootDir) {
$envvars = self::loadFromFile($rootDir . DIRECTORY_SEPARATOR . '.env');
self::MUTATE_SERVER_addEnvVars($envvars);
}
}