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.
62 lines
1.8 KiB
PHP
62 lines
1.8 KiB
PHP
<?php
|
|
namespace Gbili;
|
|
|
|
class DotEnv {
|
|
|
|
public static function loadFromFile($filepath) {
|
|
if (!file_exists($filepath)) {
|
|
throw new \Exception('Cannot find file');
|
|
}
|
|
$contents = file_get_contents($filepath);
|
|
$lines = explode(PHP_EOL, $contents);
|
|
$envvars = array_reduce($lines, function ($vars, $line) {
|
|
if (strpos(ltrim($line), '#') === 0) {
|
|
return $vars;
|
|
}
|
|
$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
|
|
);
|
|
$trimmedValue = trim($value);
|
|
$vars[trim($varname)] = self::removeOuterQuotes($trimmedValue);
|
|
return $vars;
|
|
}, []);
|
|
return $envvars;
|
|
}
|
|
|
|
public static function removeOuterQuotes(string $string, $quote = "'"): string {
|
|
$lastCharIndex = strlen($string) - 1;
|
|
$stringWithoutOuterQuotes = strpos($string, $quote) === 0 && strpos($string, $quote, -1) === $lastCharIndex
|
|
? substr($string, 1, $lastCharIndex)
|
|
: $string;
|
|
|
|
if ($quote === '"') {
|
|
return $stringWithoutOuterQuotes;
|
|
}
|
|
|
|
$noQuotesRemoved = strlen($stringWithoutOuterQuotes) === strlen($string);
|
|
|
|
if ($noQuotesRemoved && $quote === "'") {
|
|
return self::removeOuterQuotes($string, '"');
|
|
}
|
|
|
|
return $stringWithoutOuterQuotes;
|
|
}
|
|
|
|
public static function MUTATE_ENV_addEnvVars(array $variables) {
|
|
$_ENV = array_merge($_ENV, $variables);
|
|
}
|
|
|
|
public static function load(string $rootDir) {
|
|
$envvars = self::loadFromFile($rootDir . DIRECTORY_SEPARATOR . '.env');
|
|
self::MUTATE_ENV_addEnvVars($envvars);
|
|
}
|
|
|
|
} |