updated packages
This commit is contained in:
+137
-300
@@ -2,269 +2,176 @@
|
||||
|
||||
namespace Dotenv;
|
||||
|
||||
use Dotenv\Exception\InvalidFileException;
|
||||
use Dotenv\Environment\FactoryInterface;
|
||||
use Dotenv\Exception\InvalidPathException;
|
||||
use Dotenv\Regex\Regex;
|
||||
use PhpOption\Option;
|
||||
|
||||
/**
|
||||
* This is the loaded class.
|
||||
* This is the loader class.
|
||||
*
|
||||
* It's responsible for loading variables by reading a file from disk and:
|
||||
* - stripping comments beginning with a `#`,
|
||||
* - parsing lines that look shell variable setters, e.g `export key = value`, `key="value"`.
|
||||
* - multiline variable look always start with a " and end with it, e.g: `key="value
|
||||
* value"`
|
||||
*/
|
||||
class Loader
|
||||
{
|
||||
/**
|
||||
* The file path.
|
||||
* The file paths.
|
||||
*
|
||||
* @var string
|
||||
* @var string[]
|
||||
*/
|
||||
protected $filePath;
|
||||
protected $filePaths;
|
||||
|
||||
/**
|
||||
* Are we immutable?
|
||||
* The environment factory instance.
|
||||
*
|
||||
* @var bool
|
||||
* @var \Dotenv\Environment\FactoryInterface
|
||||
*/
|
||||
protected $immutable;
|
||||
protected $envFactory;
|
||||
|
||||
/**
|
||||
* The environment variables instance.
|
||||
*
|
||||
* @var \Dotenv\Environment\VariablesInterface
|
||||
*/
|
||||
protected $envVariables;
|
||||
|
||||
/**
|
||||
* The list of environment variables declared inside the 'env' file.
|
||||
*
|
||||
* @var array
|
||||
* @var string[]
|
||||
*/
|
||||
public $variableNames = array();
|
||||
protected $variableNames = [];
|
||||
|
||||
/**
|
||||
* Create a new loader instance.
|
||||
*
|
||||
* @param string $filePath
|
||||
* @param bool $immutable
|
||||
* @param string[] $filePaths
|
||||
* @param \Dotenv\Environment\FactoryInterface $envFactory
|
||||
* @param bool $immutable
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($filePath, $immutable = false)
|
||||
public function __construct(array $filePaths, FactoryInterface $envFactory, $immutable = false)
|
||||
{
|
||||
$this->filePath = $filePath;
|
||||
$this->immutable = $immutable;
|
||||
$this->filePaths = $filePaths;
|
||||
$this->envFactory = $envFactory;
|
||||
$this->setImmutable($immutable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set immutable value.
|
||||
*
|
||||
* @param bool $immutable
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setImmutable($immutable = false)
|
||||
{
|
||||
$this->immutable = $immutable;
|
||||
$this->envVariables = $immutable
|
||||
? $this->envFactory->createImmutable()
|
||||
: $this->envFactory->create();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get immutable value.
|
||||
* Load the environment file from disk.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getImmutable()
|
||||
{
|
||||
return $this->immutable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.env` file in given directory.
|
||||
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
|
||||
*
|
||||
* @return array
|
||||
* @return array<string|null>
|
||||
*/
|
||||
public function load()
|
||||
{
|
||||
$this->ensureFileIsReadable();
|
||||
|
||||
$filePath = $this->filePath;
|
||||
$lines = $this->readLinesFromFile($filePath);
|
||||
foreach ($lines as $line) {
|
||||
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
|
||||
$this->setEnvironmentVariable($line);
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
return $this->loadDirect(
|
||||
self::findAndRead($this->filePaths)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the given filePath is readable.
|
||||
* Directly load the given string.
|
||||
*
|
||||
* @throws \Dotenv\Exception\InvalidPathException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureFileIsReadable()
|
||||
{
|
||||
if (!is_readable($this->filePath) || !is_file($this->filePath)) {
|
||||
throw new InvalidPathException(sprintf('Unable to read the environment file at %s.', $this->filePath));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise the given environment variable.
|
||||
*
|
||||
* Takes value as passed in by developer and:
|
||||
* - ensures we're dealing with a separate name and value, breaking apart the name string if needed,
|
||||
* - cleaning the value of quotes,
|
||||
* - cleaning the name of quotes,
|
||||
* - resolving nested variables.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function normaliseEnvironmentVariable($name, $value)
|
||||
{
|
||||
list($name, $value) = $this->processFilters($name, $value);
|
||||
|
||||
$value = $this->resolveNestedVariables($value);
|
||||
|
||||
return array($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the runtime filters.
|
||||
*
|
||||
* Called from `normaliseEnvironmentVariable` and the `VariableFactory`, passed as a callback in `$this->loadFromFile()`.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function processFilters($name, $value)
|
||||
{
|
||||
list($name, $value) = $this->splitCompoundStringIntoParts($name, $value);
|
||||
list($name, $value) = $this->sanitiseVariableName($name, $value);
|
||||
list($name, $value) = $this->sanitiseVariableValue($name, $value);
|
||||
|
||||
return array($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read lines from the file, auto detecting line endings.
|
||||
*
|
||||
* @param string $filePath
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function readLinesFromFile($filePath)
|
||||
{
|
||||
// Read file into an array of lines with auto-detected line endings
|
||||
$autodetect = ini_get('auto_detect_line_endings');
|
||||
ini_set('auto_detect_line_endings', '1');
|
||||
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
ini_set('auto_detect_line_endings', $autodetect);
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the line in the file is a comment, e.g. begins with a #.
|
||||
*
|
||||
* @param string $line
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function isComment($line)
|
||||
{
|
||||
$line = ltrim($line);
|
||||
|
||||
return isset($line[0]) && $line[0] === '#';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given line looks like it's setting a variable.
|
||||
*
|
||||
* @param string $line
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function looksLikeSetter($line)
|
||||
{
|
||||
return strpos($line, '=') !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the compound string into parts.
|
||||
*
|
||||
* If the `$name` contains an `=` sign, then we split it into 2 parts, a `name` & `value`
|
||||
* disregarding the `$value` passed in.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function splitCompoundStringIntoParts($name, $value)
|
||||
{
|
||||
if (strpos($name, '=') !== false) {
|
||||
list($name, $value) = array_map('trim', explode('=', $name, 2));
|
||||
}
|
||||
|
||||
return array($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips quotes from the environment variable value.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
* @param string $content
|
||||
*
|
||||
* @throws \Dotenv\Exception\InvalidFileException
|
||||
*
|
||||
* @return array
|
||||
* @return array<string|null>
|
||||
*/
|
||||
protected function sanitiseVariableValue($name, $value)
|
||||
public function loadDirect($content)
|
||||
{
|
||||
$value = trim($value);
|
||||
if (!$value) {
|
||||
return array($name, $value);
|
||||
return $this->processEntries(
|
||||
Lines::process(preg_split("/(\r\n|\n|\r)/", $content))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to read the files in order.
|
||||
*
|
||||
* @param string[] $filePaths
|
||||
*
|
||||
* @throws \Dotenv\Exception\InvalidPathException
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private static function findAndRead(array $filePaths)
|
||||
{
|
||||
if ($filePaths === []) {
|
||||
throw new InvalidPathException('At least one environment file path must be provided.');
|
||||
}
|
||||
|
||||
if ($this->beginsWithAQuote($value)) { // value starts with a quote
|
||||
$quote = $value[0];
|
||||
$regexPattern = sprintf(
|
||||
'/^
|
||||
%1$s # match a quote at the start of the value
|
||||
( # capturing sub-pattern used
|
||||
(?: # we do not need to capture this
|
||||
[^%1$s\\\\]* # any character other than a quote or backslash
|
||||
|\\\\\\\\ # or two backslashes together
|
||||
|\\\\%1$s # or an escaped quote e.g \"
|
||||
)* # as many characters that match the previous rules
|
||||
) # end of the capturing sub-pattern
|
||||
%1$s # and the closing quote
|
||||
.*$ # and discard any string after the closing quote
|
||||
/mx',
|
||||
$quote
|
||||
);
|
||||
$value = preg_replace($regexPattern, '$1', $value);
|
||||
$value = str_replace("\\$quote", $quote, $value);
|
||||
$value = str_replace('\\\\', '\\', $value);
|
||||
} else {
|
||||
$parts = explode(' #', $value, 2);
|
||||
$value = trim($parts[0]);
|
||||
|
||||
// Unquoted values cannot contain whitespace
|
||||
if (preg_match('/\s+/', $value) > 0) {
|
||||
// Check if value is a comment (usually triggered when empty value with comment)
|
||||
if (preg_match('/^#/', $value) > 0) {
|
||||
$value = '';
|
||||
} else {
|
||||
throw new InvalidFileException('Dotenv values containing spaces must be surrounded by quotes.');
|
||||
}
|
||||
foreach ($filePaths as $filePath) {
|
||||
$lines = self::readFromFile($filePath);
|
||||
if ($lines->isDefined()) {
|
||||
return $lines->get();
|
||||
}
|
||||
}
|
||||
|
||||
return array($name, trim($value));
|
||||
throw new InvalidPathException(
|
||||
sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $filePaths))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the given file.
|
||||
*
|
||||
* @param string $filePath
|
||||
*
|
||||
* @return \PhpOption\Option
|
||||
*/
|
||||
private static function readFromFile($filePath)
|
||||
{
|
||||
$content = @file_get_contents($filePath);
|
||||
|
||||
return Option::fromValue($content, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the environment variable entries.
|
||||
*
|
||||
* We'll fill out any nested variables, and acually set the variable using
|
||||
* the underlying environment variables instance.
|
||||
*
|
||||
* @param string[] $entries
|
||||
*
|
||||
* @throws \Dotenv\Exception\InvalidFileException
|
||||
*
|
||||
* @return array<string|null>
|
||||
*/
|
||||
private function processEntries(array $entries)
|
||||
{
|
||||
$vars = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
list($name, $value) = Parser::parse($entry);
|
||||
$vars[$name] = $this->resolveNestedVariables($value);
|
||||
$this->setEnvironmentVariable($name, $vars[$name]);
|
||||
}
|
||||
|
||||
return $vars;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,56 +180,27 @@ class Loader
|
||||
* Look for ${varname} patterns in the variable value and replace with an
|
||||
* existing environment variable.
|
||||
*
|
||||
* @param string $value
|
||||
* @param string|null $value
|
||||
*
|
||||
* @return mixed
|
||||
* @return string|null
|
||||
*/
|
||||
protected function resolveNestedVariables($value)
|
||||
private function resolveNestedVariables($value = null)
|
||||
{
|
||||
if (strpos($value, '$') !== false) {
|
||||
$loader = $this;
|
||||
$value = preg_replace_callback(
|
||||
'/\${([a-zA-Z0-9_.]+)}/',
|
||||
function ($matchedPatterns) use ($loader) {
|
||||
$nestedVariable = $loader->getEnvironmentVariable($matchedPatterns[1]);
|
||||
if ($nestedVariable === null) {
|
||||
return $matchedPatterns[0];
|
||||
} else {
|
||||
return $nestedVariable;
|
||||
}
|
||||
},
|
||||
$value
|
||||
);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips quotes and the optional leading "export " from the environment variable name.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function sanitiseVariableName($name, $value)
|
||||
{
|
||||
$name = trim(str_replace(array('export ', '\'', '"'), '', $name));
|
||||
|
||||
return array($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given string begins with a quote.
|
||||
*
|
||||
* @param string $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function beginsWithAQuote($value)
|
||||
{
|
||||
return isset($value[0]) && ($value[0] === '"' || $value[0] === '\'');
|
||||
return Option::fromValue($value)
|
||||
->filter(function ($str) {
|
||||
return strpos($str, '$') !== false;
|
||||
})
|
||||
->flatMap(function ($str) {
|
||||
return Regex::replaceCallback(
|
||||
'/\${([a-zA-Z0-9_.]+)}/',
|
||||
function (array $matches) {
|
||||
return Option::fromValue($this->getEnvironmentVariable($matches[1]))
|
||||
->getOrElse($matches[0]);
|
||||
},
|
||||
$str
|
||||
)->success();
|
||||
})
|
||||
->getOrElse($value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -334,27 +212,12 @@ class Loader
|
||||
*/
|
||||
public function getEnvironmentVariable($name)
|
||||
{
|
||||
switch (true) {
|
||||
case array_key_exists($name, $_ENV):
|
||||
return $_ENV[$name];
|
||||
case array_key_exists($name, $_SERVER):
|
||||
return $_SERVER[$name];
|
||||
default:
|
||||
$value = getenv($name);
|
||||
return $value === false ? null : $value; // switch getenv default to null
|
||||
}
|
||||
return $this->envVariables->get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an environment variable.
|
||||
*
|
||||
* This is done using:
|
||||
* - putenv,
|
||||
* - $_ENV,
|
||||
* - $_SERVER.
|
||||
*
|
||||
* The environment variable value is stripped of single and double quotes.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string|null $value
|
||||
*
|
||||
@@ -362,57 +225,31 @@ class Loader
|
||||
*/
|
||||
public function setEnvironmentVariable($name, $value = null)
|
||||
{
|
||||
list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);
|
||||
|
||||
$this->variableNames[] = $name;
|
||||
|
||||
// Don't overwrite existing environment variables if we're immutable
|
||||
// Ruby's dotenv does this with `ENV[key] ||= value`.
|
||||
if ($this->immutable && $this->getEnvironmentVariable($name) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If PHP is running as an Apache module and an existing
|
||||
// Apache environment variable exists, overwrite it
|
||||
if (function_exists('apache_getenv') && function_exists('apache_setenv') && apache_getenv($name) !== false) {
|
||||
apache_setenv($name, $value);
|
||||
}
|
||||
|
||||
if (function_exists('putenv')) {
|
||||
putenv("$name=$value");
|
||||
}
|
||||
|
||||
$_ENV[$name] = $value;
|
||||
$_SERVER[$name] = $value;
|
||||
$this->envVariables->set($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear an environment variable.
|
||||
*
|
||||
* This is not (currently) used by Dotenv but is provided as a utility
|
||||
* method for 3rd party code.
|
||||
*
|
||||
* This is done using:
|
||||
* - putenv,
|
||||
* - unset($_ENV, $_SERVER).
|
||||
* This method only expects names in normal form.
|
||||
*
|
||||
* @param string $name
|
||||
*
|
||||
* @see setEnvironmentVariable()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearEnvironmentVariable($name)
|
||||
{
|
||||
// Don't clear anything if we're immutable.
|
||||
if ($this->immutable) {
|
||||
return;
|
||||
}
|
||||
$this->envVariables->clear($name);
|
||||
}
|
||||
|
||||
if (function_exists('putenv')) {
|
||||
putenv($name);
|
||||
}
|
||||
|
||||
unset($_ENV[$name], $_SERVER[$name]);
|
||||
/**
|
||||
* Get the list of environment variables names.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getEnvironmentVariableNames()
|
||||
{
|
||||
return $this->variableNames;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user