first commit

This commit is contained in:
Roman Pyrih
2023-07-24 08:30:51 +02:00
commit c2e100a763
7128 changed files with 1622619 additions and 0 deletions

View File

@@ -0,0 +1,571 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv;
use Symfony\Component\Dotenv\Exception\FormatException;
use Symfony\Component\Dotenv\Exception\FormatExceptionContext;
use Symfony\Component\Dotenv\Exception\PathException;
use Symfony\Component\Process\Exception\ExceptionInterface as ProcessException;
use Symfony\Component\Process\Process;
/**
* Manages .env files.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class Dotenv
{
public const VARNAME_REGEX = '(?i:[A-Z][A-Z0-9_]*+)';
public const STATE_VARNAME = 0;
public const STATE_VALUE = 1;
private $path;
private $cursor;
private $lineno;
private $data;
private $end;
private $values;
private $envKey;
private $debugKey;
private $prodEnvs = ['prod'];
private $usePutenv = false;
/**
* @param string $envKey
*/
public function __construct($envKey = 'APP_ENV', string $debugKey = 'APP_DEBUG')
{
if (\in_array($envKey = (string) $envKey, ['1', ''], true)) {
trigger_deprecation('symfony/dotenv', '5.1', 'Passing a boolean to the constructor of "%s" is deprecated, use "Dotenv::usePutenv()".', __CLASS__);
$this->usePutenv = (bool) $envKey;
$envKey = 'APP_ENV';
}
$this->envKey = $envKey;
$this->debugKey = $debugKey;
}
/**
* @return $this
*/
public function setProdEnvs(array $prodEnvs): self
{
$this->prodEnvs = $prodEnvs;
return $this;
}
/**
* @param bool $usePutenv If `putenv()` should be used to define environment variables or not.
* Beware that `putenv()` is not thread safe, that's why this setting defaults to false
*
* @return $this
*/
public function usePutenv(bool $usePutenv = true): self
{
$this->usePutenv = $usePutenv;
return $this;
}
/**
* Loads one or several .env files.
*
* @param string $path A file to load
* @param ...string $extraPaths A list of additional files to load
*
* @throws FormatException when a file has a syntax error
* @throws PathException when a file does not exist or is not readable
*/
public function load(string $path, string ...$extraPaths): void
{
$this->doLoad(false, \func_get_args());
}
/**
* Loads a .env file and the corresponding .env.local, .env.$env and .env.$env.local files if they exist.
*
* .env.local is always ignored in test env because tests should produce the same results for everyone.
* .env.dist is loaded when it exists and .env is not found.
*
* @param string $path A file to load
* @param string $envKey|null The name of the env vars that defines the app env
* @param string $defaultEnv The app env to use when none is defined
* @param array $testEnvs A list of app envs for which .env.local should be ignored
*
* @throws FormatException when a file has a syntax error
* @throws PathException when a file does not exist or is not readable
*/
public function loadEnv(string $path, string $envKey = null, string $defaultEnv = 'dev', array $testEnvs = ['test']): void
{
$k = $envKey ?? $this->envKey;
if (is_file($path) || !is_file($p = "$path.dist")) {
$this->load($path);
} else {
$this->load($p);
}
if (null === $env = $_SERVER[$k] ?? $_ENV[$k] ?? null) {
$this->populate([$k => $env = $defaultEnv]);
}
if (!\in_array($env, $testEnvs, true) && is_file($p = "$path.local")) {
$this->load($p);
$env = $_SERVER[$k] ?? $_ENV[$k] ?? $env;
}
if ('local' === $env) {
return;
}
if (is_file($p = "$path.$env")) {
$this->load($p);
}
if (is_file($p = "$path.$env.local")) {
$this->load($p);
}
}
/**
* Loads env vars from .env.local.php if the file exists or from the other .env files otherwise.
*
* This method also configures the APP_DEBUG env var according to the current APP_ENV.
*
* See method loadEnv() for rules related to .env files.
*/
public function bootEnv(string $path, string $defaultEnv = 'dev', array $testEnvs = ['test']): void
{
$p = $path.'.local.php';
$env = is_file($p) ? include $p : null;
$k = $this->envKey;
if (\is_array($env) && (!isset($env[$k]) || ($_SERVER[$k] ?? $_ENV[$k] ?? $env[$k]) === $env[$k])) {
$this->populate($env);
} else {
$this->loadEnv($path, $k, $defaultEnv, $testEnvs);
}
$_SERVER += $_ENV;
$k = $this->debugKey;
$debug = $_SERVER[$k] ?? !\in_array($_SERVER[$this->envKey], $this->prodEnvs, true);
$_SERVER[$k] = $_ENV[$k] = (int) $debug || (!\is_bool($debug) && filter_var($debug, \FILTER_VALIDATE_BOOLEAN)) ? '1' : '0';
}
/**
* Loads one or several .env files and enables override existing vars.
*
* @param string $path A file to load
* @param ...string $extraPaths A list of additional files to load
*
* @throws FormatException when a file has a syntax error
* @throws PathException when a file does not exist or is not readable
*/
public function overload(string $path, string ...$extraPaths): void
{
$this->doLoad(true, \func_get_args());
}
/**
* Sets values as environment variables (via putenv, $_ENV, and $_SERVER).
*
* @param array $values An array of env variables
* @param bool $overrideExistingVars true when existing environment variables must be overridden
*/
public function populate(array $values, bool $overrideExistingVars = false): void
{
$updateLoadedVars = false;
$loadedVars = array_flip(explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? ''));
foreach ($values as $name => $value) {
$notHttpName = 0 !== strpos($name, 'HTTP_');
// don't check existence with getenv() because of thread safety issues
if (!isset($loadedVars[$name]) && (!$overrideExistingVars && (isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)))) {
continue;
}
if ($this->usePutenv) {
putenv("$name=$value");
}
$_ENV[$name] = $value;
if ($notHttpName) {
$_SERVER[$name] = $value;
}
if (!isset($loadedVars[$name])) {
$loadedVars[$name] = $updateLoadedVars = true;
}
}
if ($updateLoadedVars) {
unset($loadedVars['']);
$loadedVars = implode(',', array_keys($loadedVars));
$_ENV['SYMFONY_DOTENV_VARS'] = $_SERVER['SYMFONY_DOTENV_VARS'] = $loadedVars;
if ($this->usePutenv) {
putenv('SYMFONY_DOTENV_VARS='.$loadedVars);
}
}
}
/**
* Parses the contents of an .env file.
*
* @param string $data The data to be parsed
* @param string $path The original file name where data where stored (used for more meaningful error messages)
*
* @return array
*
* @throws FormatException when a file has a syntax error
*/
public function parse(string $data, string $path = '.env'): array
{
$this->path = $path;
$this->data = str_replace(["\r\n", "\r"], "\n", $data);
$this->lineno = 1;
$this->cursor = 0;
$this->end = \strlen($this->data);
$state = self::STATE_VARNAME;
$this->values = [];
$name = '';
$this->skipEmptyLines();
while ($this->cursor < $this->end) {
switch ($state) {
case self::STATE_VARNAME:
$name = $this->lexVarname();
$state = self::STATE_VALUE;
break;
case self::STATE_VALUE:
$this->values[$name] = $this->lexValue();
$state = self::STATE_VARNAME;
break;
}
}
if (self::STATE_VALUE === $state) {
$this->values[$name] = '';
}
try {
return $this->values;
} finally {
$this->values = [];
$this->data = null;
$this->path = null;
}
}
private function lexVarname(): string
{
// var name + optional export
if (!preg_match('/(export[ \t]++)?('.self::VARNAME_REGEX.')/A', $this->data, $matches, 0, $this->cursor)) {
throw $this->createFormatException('Invalid character in variable name');
}
$this->moveCursor($matches[0]);
if ($this->cursor === $this->end || "\n" === $this->data[$this->cursor] || '#' === $this->data[$this->cursor]) {
if ($matches[1]) {
throw $this->createFormatException('Unable to unset an environment variable');
}
throw $this->createFormatException('Missing = in the environment variable declaration');
}
if (' ' === $this->data[$this->cursor] || "\t" === $this->data[$this->cursor]) {
throw $this->createFormatException('Whitespace characters are not supported after the variable name');
}
if ('=' !== $this->data[$this->cursor]) {
throw $this->createFormatException('Missing = in the environment variable declaration');
}
++$this->cursor;
return $matches[2];
}
private function lexValue(): string
{
if (preg_match('/[ \t]*+(?:#.*)?$/Am', $this->data, $matches, 0, $this->cursor)) {
$this->moveCursor($matches[0]);
$this->skipEmptyLines();
return '';
}
if (' ' === $this->data[$this->cursor] || "\t" === $this->data[$this->cursor]) {
throw $this->createFormatException('Whitespace are not supported before the value');
}
$loadedVars = array_flip(explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? ($_ENV['SYMFONY_DOTENV_VARS'] ?? '')));
unset($loadedVars['']);
$v = '';
do {
if ("'" === $this->data[$this->cursor]) {
$len = 0;
do {
if ($this->cursor + ++$len === $this->end) {
$this->cursor += $len;
throw $this->createFormatException('Missing quote to end the value');
}
} while ("'" !== $this->data[$this->cursor + $len]);
$v .= substr($this->data, 1 + $this->cursor, $len - 1);
$this->cursor += 1 + $len;
} elseif ('"' === $this->data[$this->cursor]) {
$value = '';
if (++$this->cursor === $this->end) {
throw $this->createFormatException('Missing quote to end the value');
}
while ('"' !== $this->data[$this->cursor] || ('\\' === $this->data[$this->cursor - 1] && '\\' !== $this->data[$this->cursor - 2])) {
$value .= $this->data[$this->cursor];
++$this->cursor;
if ($this->cursor === $this->end) {
throw $this->createFormatException('Missing quote to end the value');
}
}
++$this->cursor;
$value = str_replace(['\\"', '\r', '\n'], ['"', "\r", "\n"], $value);
$resolvedValue = $value;
$resolvedValue = $this->resolveVariables($resolvedValue, $loadedVars);
$resolvedValue = $this->resolveCommands($resolvedValue, $loadedVars);
$resolvedValue = str_replace('\\\\', '\\', $resolvedValue);
$v .= $resolvedValue;
} else {
$value = '';
$prevChr = $this->data[$this->cursor - 1];
while ($this->cursor < $this->end && !\in_array($this->data[$this->cursor], ["\n", '"', "'"], true) && !((' ' === $prevChr || "\t" === $prevChr) && '#' === $this->data[$this->cursor])) {
if ('\\' === $this->data[$this->cursor] && isset($this->data[$this->cursor + 1]) && ('"' === $this->data[$this->cursor + 1] || "'" === $this->data[$this->cursor + 1])) {
++$this->cursor;
}
$value .= $prevChr = $this->data[$this->cursor];
if ('$' === $this->data[$this->cursor] && isset($this->data[$this->cursor + 1]) && '(' === $this->data[$this->cursor + 1]) {
++$this->cursor;
$value .= '('.$this->lexNestedExpression().')';
}
++$this->cursor;
}
$value = rtrim($value);
$resolvedValue = $value;
$resolvedValue = $this->resolveVariables($resolvedValue, $loadedVars);
$resolvedValue = $this->resolveCommands($resolvedValue, $loadedVars);
$resolvedValue = str_replace('\\\\', '\\', $resolvedValue);
if ($resolvedValue === $value && preg_match('/\s+/', $value)) {
throw $this->createFormatException('A value containing spaces must be surrounded by quotes');
}
$v .= $resolvedValue;
if ($this->cursor < $this->end && '#' === $this->data[$this->cursor]) {
break;
}
}
} while ($this->cursor < $this->end && "\n" !== $this->data[$this->cursor]);
$this->skipEmptyLines();
return $v;
}
private function lexNestedExpression(): string
{
++$this->cursor;
$value = '';
while ("\n" !== $this->data[$this->cursor] && ')' !== $this->data[$this->cursor]) {
$value .= $this->data[$this->cursor];
if ('(' === $this->data[$this->cursor]) {
$value .= $this->lexNestedExpression().')';
}
++$this->cursor;
if ($this->cursor === $this->end) {
throw $this->createFormatException('Missing closing parenthesis.');
}
}
if ("\n" === $this->data[$this->cursor]) {
throw $this->createFormatException('Missing closing parenthesis.');
}
return $value;
}
private function skipEmptyLines()
{
if (preg_match('/(?:\s*+(?:#[^\n]*+)?+)++/A', $this->data, $match, 0, $this->cursor)) {
$this->moveCursor($match[0]);
}
}
private function resolveCommands(string $value, array $loadedVars): string
{
if (false === strpos($value, '$')) {
return $value;
}
$regex = '/
(\\\\)? # escaped with a backslash?
\$
(?<cmd>
\( # require opening parenthesis
([^()]|\g<cmd>)+ # allow any number of non-parens, or balanced parens (by nesting the <cmd> expression recursively)
\) # require closing paren
)
/x';
return preg_replace_callback($regex, function ($matches) use ($loadedVars) {
if ('\\' === $matches[1]) {
return substr($matches[0], 1);
}
if ('\\' === \DIRECTORY_SEPARATOR) {
throw new \LogicException('Resolving commands is not supported on Windows.');
}
if (!class_exists(Process::class)) {
throw new \LogicException('Resolving commands requires the Symfony Process component.');
}
$process = method_exists(Process::class, 'fromShellCommandline') ? Process::fromShellCommandline('echo '.$matches[0]) : new Process('echo '.$matches[0]);
if (!method_exists(Process::class, 'fromShellCommandline') && method_exists(Process::class, 'inheritEnvironmentVariables')) {
// Symfony 3.4 does not inherit env vars by default:
$process->inheritEnvironmentVariables();
}
$env = [];
foreach ($this->values as $name => $value) {
if (isset($loadedVars[$name]) || (!isset($_ENV[$name]) && !(isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')))) {
$env[$name] = $value;
}
}
$process->setEnv($env);
try {
$process->mustRun();
} catch (ProcessException $e) {
throw $this->createFormatException(sprintf('Issue expanding a command (%s)', $process->getErrorOutput()));
}
return preg_replace('/[\r\n]+$/', '', $process->getOutput());
}, $value);
}
private function resolveVariables(string $value, array $loadedVars): string
{
if (false === strpos($value, '$')) {
return $value;
}
$regex = '/
(?<!\\\\)
(?P<backslashes>\\\\*) # escaped with a backslash?
\$
(?!\() # no opening parenthesis
(?P<opening_brace>\{)? # optional brace
(?P<name>'.self::VARNAME_REGEX.')? # var name
(?P<default_value>:[-=][^\}]++)? # optional default value
(?P<closing_brace>\})? # optional closing brace
/x';
$value = preg_replace_callback($regex, function ($matches) use ($loadedVars) {
// odd number of backslashes means the $ character is escaped
if (1 === \strlen($matches['backslashes']) % 2) {
return substr($matches[0], 1);
}
// unescaped $ not followed by variable name
if (!isset($matches['name'])) {
return $matches[0];
}
if ('{' === $matches['opening_brace'] && !isset($matches['closing_brace'])) {
throw $this->createFormatException('Unclosed braces on variable expansion');
}
$name = $matches['name'];
if (isset($loadedVars[$name]) && isset($this->values[$name])) {
$value = $this->values[$name];
} elseif (isset($_ENV[$name])) {
$value = $_ENV[$name];
} elseif (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) {
$value = $_SERVER[$name];
} elseif (isset($this->values[$name])) {
$value = $this->values[$name];
} else {
$value = (string) getenv($name);
}
if ('' === $value && isset($matches['default_value']) && '' !== $matches['default_value']) {
$unsupportedChars = strpbrk($matches['default_value'], '\'"{$');
if (false !== $unsupportedChars) {
throw $this->createFormatException(sprintf('Unsupported character "%s" found in the default value of variable "$%s".', $unsupportedChars[0], $name));
}
$value = substr($matches['default_value'], 2);
if ('=' === $matches['default_value'][1]) {
$this->values[$name] = $value;
}
}
if (!$matches['opening_brace'] && isset($matches['closing_brace'])) {
$value .= '}';
}
return $matches['backslashes'].$value;
}, $value);
return $value;
}
private function moveCursor(string $text)
{
$this->cursor += \strlen($text);
$this->lineno += substr_count($text, "\n");
}
private function createFormatException(string $message): FormatException
{
return new FormatException($message, new FormatExceptionContext($this->data, $this->path, $this->lineno, $this->cursor));
}
private function doLoad(bool $overrideExistingVars, array $paths): void
{
foreach ($paths as $path) {
if (!is_readable($path) || is_dir($path)) {
throw new PathException($path);
}
$this->populate($this->parse(file_get_contents($path), $path), $overrideExistingVars);
}
}
}

View File

@@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv\Exception;
/**
* Interface for exceptions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ExceptionInterface extends \Throwable
{
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv\Exception;
/**
* Thrown when a file has a syntax error.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
final class FormatException extends \LogicException implements ExceptionInterface
{
private $context;
public function __construct(string $message, FormatExceptionContext $context, int $code = 0, \Throwable $previous = null)
{
$this->context = $context;
parent::__construct(sprintf("%s in \"%s\" at line %d.\n%s", $message, $context->getPath(), $context->getLineno(), $context->getDetails()), $code, $previous);
}
public function getContext(): FormatExceptionContext
{
return $this->context;
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv\Exception;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
final class FormatExceptionContext
{
private $data;
private $path;
private $lineno;
private $cursor;
public function __construct(string $data, string $path, int $lineno, int $cursor)
{
$this->data = $data;
$this->path = $path;
$this->lineno = $lineno;
$this->cursor = $cursor;
}
public function getPath(): string
{
return $this->path;
}
public function getLineno(): int
{
return $this->lineno;
}
public function getDetails(): string
{
$before = str_replace("\n", '\n', substr($this->data, max(0, $this->cursor - 20), min(20, $this->cursor)));
$after = str_replace("\n", '\n', substr($this->data, $this->cursor, 20));
return '...'.$before.$after."...\n".str_repeat(' ', \strlen($before) + 2).'^ line '.$this->lineno.' offset '.$this->cursor;
}
}

View File

@@ -0,0 +1,25 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv\Exception;
/**
* Thrown when a file does not exist or is not readable.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
final class PathException extends \RuntimeException implements ExceptionInterface
{
public function __construct(string $path, int $code = 0, \Throwable $previous = null)
{
parent::__construct(sprintf('Unable to read the "%s" environment file.', $path), $code, $previous);
}
}

View File

@@ -0,0 +1,19 @@
Copyright (c) 2016-2021 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,500 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Dotenv\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\Dotenv\Exception\FormatException;
use Symfony\Component\Dotenv\Exception\PathException;
class DotenvTest extends TestCase
{
/**
* @dataProvider getEnvDataWithFormatErrors
*/
public function testParseWithFormatError($data, $error)
{
$dotenv = new Dotenv();
try {
$dotenv->parse($data);
$this->fail('Should throw a FormatException');
} catch (FormatException $e) {
$this->assertStringMatchesFormat($error, $e->getMessage());
}
}
public function getEnvDataWithFormatErrors()
{
$tests = [
['FOO=BAR BAZ', "A value containing spaces must be surrounded by quotes in \".env\" at line 1.\n...FOO=BAR BAZ...\n ^ line 1 offset 11"],
['FOO BAR=BAR', "Whitespace characters are not supported after the variable name in \".env\" at line 1.\n...FOO BAR=BAR...\n ^ line 1 offset 3"],
['FOO', "Missing = in the environment variable declaration in \".env\" at line 1.\n...FOO...\n ^ line 1 offset 3"],
['FOO="foo', "Missing quote to end the value in \".env\" at line 1.\n...FOO=\"foo...\n ^ line 1 offset 8"],
['FOO=\'foo', "Missing quote to end the value in \".env\" at line 1.\n...FOO='foo...\n ^ line 1 offset 8"],
["FOO=\"foo\nBAR=\"bar\"", "Missing quote to end the value in \".env\" at line 1.\n...FOO=\"foo\\nBAR=\"bar\"...\n ^ line 1 offset 18"],
['FOO=\'foo'."\n", "Missing quote to end the value in \".env\" at line 1.\n...FOO='foo\\n...\n ^ line 1 offset 9"],
['export FOO', "Unable to unset an environment variable in \".env\" at line 1.\n...export FOO...\n ^ line 1 offset 10"],
['FOO=${FOO', "Unclosed braces on variable expansion in \".env\" at line 1.\n...FOO=\${FOO...\n ^ line 1 offset 9"],
['FOO= BAR', "Whitespace are not supported before the value in \".env\" at line 1.\n...FOO= BAR...\n ^ line 1 offset 4"],
['Стасян', "Invalid character in variable name in \".env\" at line 1.\n...Стасян...\n ^ line 1 offset 0"],
['FOO!', "Missing = in the environment variable declaration in \".env\" at line 1.\n...FOO!...\n ^ line 1 offset 3"],
['FOO=$(echo foo', "Missing closing parenthesis. in \".env\" at line 1.\n...FOO=$(echo foo...\n ^ line 1 offset 14"],
['FOO=$(echo foo'."\n", "Missing closing parenthesis. in \".env\" at line 1.\n...FOO=$(echo foo\\n...\n ^ line 1 offset 14"],
["FOO=\nBAR=\${FOO:-\'a{a}a}", "Unsupported character \"'\" found in the default value of variable \"\$FOO\". in \".env\" at line 2.\n...\\nBAR=\${FOO:-\'a{a}a}...\n ^ line 2 offset 24"],
["FOO=\nBAR=\${FOO:-a\$a}", "Unsupported character \"\$\" found in the default value of variable \"\$FOO\". in \".env\" at line 2.\n...FOO=\\nBAR=\${FOO:-a\$a}...\n ^ line 2 offset 20"],
["FOO=\nBAR=\${FOO:-a\"a}", "Unclosed braces on variable expansion in \".env\" at line 2.\n...FOO=\\nBAR=\${FOO:-a\"a}...\n ^ line 2 offset 17"],
];
if ('\\' !== \DIRECTORY_SEPARATOR) {
$tests[] = ['FOO=$((1dd2))', "Issue expanding a command (%s\n) in \".env\" at line 1.\n...FOO=$((1dd2))...\n ^ line 1 offset 13"];
}
return $tests;
}
/**
* @dataProvider getEnvData
*/
public function testParse($data, $expected)
{
$dotenv = new Dotenv();
$this->assertSame($expected, $dotenv->parse($data));
}
public function getEnvData()
{
putenv('LOCAL=local');
$_ENV['LOCAL'] = 'local';
$_ENV['REMOTE'] = 'remote';
$_SERVER['SERVERVAR'] = 'servervar';
$tests = [
// backslashes
['FOO=foo\\\\bar', ['FOO' => 'foo\\bar']],
["FOO='foo\\\\bar'", ['FOO' => 'foo\\\\bar']],
['FOO="foo\\\\bar"', ['FOO' => 'foo\\bar']],
// escaped backslash in front of variable
["BAR=bar\nFOO=foo\\\\\$BAR", ['BAR' => 'bar', 'FOO' => 'foo\\bar']],
["BAR=bar\nFOO='foo\\\\\$BAR'", ['BAR' => 'bar', 'FOO' => 'foo\\\\$BAR']],
["BAR=bar\nFOO=\"foo\\\\\$BAR\"", ['BAR' => 'bar', 'FOO' => 'foo\\bar']],
['FOO=foo\\\\\\$BAR', ['FOO' => 'foo\\$BAR']],
['FOO=\'foo\\\\\\$BAR\'', ['FOO' => 'foo\\\\\\$BAR']],
['FOO="foo\\\\\\$BAR"', ['FOO' => 'foo\\$BAR']],
// spaces
['FOO=bar', ['FOO' => 'bar']],
[' FOO=bar ', ['FOO' => 'bar']],
['FOO=', ['FOO' => '']],
["FOO=\n\n\nBAR=bar", ['FOO' => '', 'BAR' => 'bar']],
['FOO= ', ['FOO' => '']],
["FOO=\nBAR=bar", ['FOO' => '', 'BAR' => 'bar']],
// newlines
["\n\nFOO=bar\r\n\n", ['FOO' => 'bar']],
["FOO=bar\r\nBAR=foo", ['FOO' => 'bar', 'BAR' => 'foo']],
["FOO=bar\rBAR=foo", ['FOO' => 'bar', 'BAR' => 'foo']],
["FOO=bar\nBAR=foo", ['FOO' => 'bar', 'BAR' => 'foo']],
// quotes
["FOO=\"bar\"\n", ['FOO' => 'bar']],
["FOO=\"bar'foo\"\n", ['FOO' => 'bar\'foo']],
["FOO='bar'\n", ['FOO' => 'bar']],
["FOO='bar\"foo'\n", ['FOO' => 'bar"foo']],
["FOO=\"bar\\\"foo\"\n", ['FOO' => 'bar"foo']],
['FOO="bar\nfoo"', ['FOO' => "bar\nfoo"]],
['FOO="bar\rfoo"', ['FOO' => "bar\rfoo"]],
['FOO=\'bar\nfoo\'', ['FOO' => 'bar\nfoo']],
['FOO=\'bar\rfoo\'', ['FOO' => 'bar\rfoo']],
["FOO='bar\nfoo'", ['FOO' => "bar\nfoo"]],
['FOO=" FOO "', ['FOO' => ' FOO ']],
['FOO=" "', ['FOO' => ' ']],
['PATH="c:\\\\"', ['PATH' => 'c:\\']],
["FOO=\"bar\nfoo\"", ['FOO' => "bar\nfoo"]],
['FOO=BAR\\"', ['FOO' => 'BAR"']],
["FOO=BAR\\'BAZ", ['FOO' => "BAR'BAZ"]],
['FOO=\\"BAR', ['FOO' => '"BAR']],
// concatenated values
["FOO='bar''foo'\n", ['FOO' => 'barfoo']],
["FOO='bar '' baz'", ['FOO' => 'bar baz']],
["FOO=bar\nBAR='baz'\"\$FOO\"", ['FOO' => 'bar', 'BAR' => 'bazbar']],
["FOO='bar '\\'' baz'", ['FOO' => "bar ' baz"]],
// comments
["#FOO=bar\nBAR=foo", ['BAR' => 'foo']],
["#FOO=bar # Comment\nBAR=foo", ['BAR' => 'foo']],
["FOO='bar foo' # Comment", ['FOO' => 'bar foo']],
["FOO='bar#foo' # Comment", ['FOO' => 'bar#foo']],
["# Comment\r\nFOO=bar\n# Comment\nBAR=foo", ['FOO' => 'bar', 'BAR' => 'foo']],
["FOO=bar # Another comment\nBAR=foo", ['FOO' => 'bar', 'BAR' => 'foo']],
["FOO=\n\n# comment\nBAR=bar", ['FOO' => '', 'BAR' => 'bar']],
['FOO=NOT#COMMENT', ['FOO' => 'NOT#COMMENT']],
['FOO= # Comment', ['FOO' => '']],
// edge cases (no conversions, only strings as values)
['FOO=0', ['FOO' => '0']],
['FOO=false', ['FOO' => 'false']],
['FOO=null', ['FOO' => 'null']],
// export
['export FOO=bar', ['FOO' => 'bar']],
[' export FOO=bar', ['FOO' => 'bar']],
// variable expansion
["FOO=BAR\nBAR=\$FOO", ['FOO' => 'BAR', 'BAR' => 'BAR']],
["FOO=BAR\nBAR=\"\$FOO\"", ['FOO' => 'BAR', 'BAR' => 'BAR']],
["FOO=BAR\nBAR='\$FOO'", ['FOO' => 'BAR', 'BAR' => '$FOO']],
["FOO_BAR9=BAR\nBAR=\$FOO_BAR9", ['FOO_BAR9' => 'BAR', 'BAR' => 'BAR']],
["FOO=BAR\nBAR=\${FOO}Z", ['FOO' => 'BAR', 'BAR' => 'BARZ']],
["FOO=BAR\nBAR=\$FOO}", ['FOO' => 'BAR', 'BAR' => 'BAR}']],
["FOO=BAR\nBAR=\\\$FOO", ['FOO' => 'BAR', 'BAR' => '$FOO']],
['FOO=" \\$ "', ['FOO' => ' $ ']],
['FOO=" $ "', ['FOO' => ' $ ']],
['BAR=$LOCAL', ['BAR' => 'local']],
['BAR=$REMOTE', ['BAR' => 'remote']],
['BAR=$SERVERVAR', ['BAR' => 'servervar']],
['FOO=$NOTDEFINED', ['FOO' => '']],
["FOO=BAR\nBAR=\${FOO:-TEST}", ['FOO' => 'BAR', 'BAR' => 'BAR']],
["FOO=BAR\nBAR=\${NOTDEFINED:-TEST}", ['FOO' => 'BAR', 'BAR' => 'TEST']],
["FOO=\nBAR=\${FOO:-TEST}", ['FOO' => '', 'BAR' => 'TEST']],
["FOO=\nBAR=\$FOO:-TEST}", ['FOO' => '', 'BAR' => 'TEST}']],
["FOO=BAR\nBAR=\${FOO:=TEST}", ['FOO' => 'BAR', 'BAR' => 'BAR']],
["FOO=BAR\nBAR=\${NOTDEFINED:=TEST}", ['FOO' => 'BAR', 'NOTDEFINED' => 'TEST', 'BAR' => 'TEST']],
["FOO=\nBAR=\${FOO:=TEST}", ['FOO' => 'TEST', 'BAR' => 'TEST']],
["FOO=\nBAR=\$FOO:=TEST}", ['FOO' => 'TEST', 'BAR' => 'TEST}']],
["FOO=foo\nFOOBAR=\${FOO}\${BAR}", ['FOO' => 'foo', 'FOOBAR' => 'foo']],
];
if ('\\' !== \DIRECTORY_SEPARATOR) {
$tests = array_merge($tests, [
// command expansion
['FOO=$(echo foo)', ['FOO' => 'foo']],
['FOO=$((1+2))', ['FOO' => '3']],
['FOO=FOO$((1+2))BAR', ['FOO' => 'FOO3BAR']],
['FOO=$(echo "$(echo "$(echo "$(echo foo)")")")', ['FOO' => 'foo']],
["FOO=$(echo \"Quotes won't be a problem\")", ['FOO' => 'Quotes won\'t be a problem']],
["FOO=bar\nBAR=$(echo \"FOO is \$FOO\")", ['FOO' => 'bar', 'BAR' => 'FOO is bar']],
]);
}
return $tests;
}
public function testLoad()
{
unset($_ENV['FOO']);
unset($_ENV['BAR']);
unset($_SERVER['FOO']);
unset($_SERVER['BAR']);
putenv('FOO');
putenv('BAR');
@mkdir($tmpdir = sys_get_temp_dir().'/dotenv');
$path1 = tempnam($tmpdir, 'sf-');
$path2 = tempnam($tmpdir, 'sf-');
file_put_contents($path1, 'FOO=BAR');
file_put_contents($path2, 'BAR=BAZ');
(new Dotenv())->usePutenv()->load($path1, $path2);
$foo = getenv('FOO');
$bar = getenv('BAR');
putenv('FOO');
putenv('BAR');
unlink($path1);
unlink($path2);
rmdir($tmpdir);
$this->assertSame('BAR', $foo);
$this->assertSame('BAZ', $bar);
}
public function testLoadEnv()
{
unset($_ENV['FOO']);
unset($_ENV['BAR']);
unset($_SERVER['FOO']);
unset($_SERVER['BAR']);
putenv('FOO');
putenv('BAR');
@mkdir($tmpdir = sys_get_temp_dir().'/dotenv');
$path = tempnam($tmpdir, 'sf-');
// .env
file_put_contents($path, 'FOO=BAR');
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('BAR', getenv('FOO'));
$this->assertSame('dev', getenv('TEST_APP_ENV'));
// .env.local
$_SERVER['TEST_APP_ENV'] = 'local';
file_put_contents("$path.local", 'FOO=localBAR');
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('localBAR', getenv('FOO'));
// special case for test
$_SERVER['TEST_APP_ENV'] = 'test';
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('BAR', getenv('FOO'));
// .env.dev
unset($_SERVER['TEST_APP_ENV']);
file_put_contents("$path.dev", 'FOO=devBAR');
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('devBAR', getenv('FOO'));
// .env.dev.local
file_put_contents("$path.dev.local", 'FOO=devlocalBAR');
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('devlocalBAR', getenv('FOO'));
// .env.dist
unlink($path);
file_put_contents("$path.dist", 'BAR=distBAR');
(new Dotenv())->usePutenv()->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('distBAR', getenv('BAR'));
putenv('FOO');
putenv('BAR');
unlink("$path.dist");
unlink("$path.local");
unlink("$path.dev");
unlink("$path.dev.local");
rmdir($tmpdir);
}
public function testOverload()
{
unset($_ENV['FOO']);
unset($_ENV['BAR']);
unset($_SERVER['FOO']);
unset($_SERVER['BAR']);
putenv('FOO=initial_foo_value');
putenv('BAR=initial_bar_value');
$_ENV['FOO'] = 'initial_foo_value';
$_ENV['BAR'] = 'initial_bar_value';
@mkdir($tmpdir = sys_get_temp_dir().'/dotenv');
$path1 = tempnam($tmpdir, 'sf-');
$path2 = tempnam($tmpdir, 'sf-');
file_put_contents($path1, 'FOO=BAR');
file_put_contents($path2, 'BAR=BAZ');
(new Dotenv())->usePutenv()->overload($path1, $path2);
$foo = getenv('FOO');
$bar = getenv('BAR');
putenv('FOO');
putenv('BAR');
unlink($path1);
unlink($path2);
rmdir($tmpdir);
$this->assertSame('BAR', $foo);
$this->assertSame('BAZ', $bar);
}
public function testLoadDirectory()
{
$this->expectException(PathException::class);
$dotenv = new Dotenv();
$dotenv->load(__DIR__);
}
public function testServerSuperglobalIsNotOverridden()
{
$originalValue = $_SERVER['argc'];
$dotenv = new Dotenv();
$dotenv->populate(['argc' => 'new_value']);
$this->assertSame($originalValue, $_SERVER['argc']);
}
public function testEnvVarIsNotOverridden()
{
putenv('TEST_ENV_VAR=original_value');
$_SERVER['TEST_ENV_VAR'] = 'original_value';
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['TEST_ENV_VAR' => 'new_value']);
$this->assertSame('original_value', getenv('TEST_ENV_VAR'));
}
public function testHttpVarIsPartiallyOverridden()
{
$_SERVER['HTTP_TEST_ENV_VAR'] = 'http_value';
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['HTTP_TEST_ENV_VAR' => 'env_value']);
$this->assertSame('env_value', getenv('HTTP_TEST_ENV_VAR'));
$this->assertSame('env_value', $_ENV['HTTP_TEST_ENV_VAR']);
$this->assertSame('http_value', $_SERVER['HTTP_TEST_ENV_VAR']);
}
public function testEnvVarIsOverriden()
{
putenv('TEST_ENV_VAR_OVERRIDEN=original_value');
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['TEST_ENV_VAR_OVERRIDEN' => 'new_value'], true);
$this->assertSame('new_value', getenv('TEST_ENV_VAR_OVERRIDEN'));
$this->assertSame('new_value', $_ENV['TEST_ENV_VAR_OVERRIDEN']);
$this->assertSame('new_value', $_SERVER['TEST_ENV_VAR_OVERRIDEN']);
}
public function testMemorizingLoadedVarsNamesInSpecialVar()
{
// Special variable not exists
unset($_ENV['SYMFONY_DOTENV_VARS']);
unset($_SERVER['SYMFONY_DOTENV_VARS']);
putenv('SYMFONY_DOTENV_VARS');
unset($_ENV['APP_DEBUG']);
unset($_SERVER['APP_DEBUG']);
putenv('APP_DEBUG');
unset($_ENV['DATABASE_URL']);
unset($_SERVER['DATABASE_URL']);
putenv('DATABASE_URL');
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['APP_DEBUG' => '1', 'DATABASE_URL' => 'mysql://root@localhost/db']);
$this->assertSame('APP_DEBUG,DATABASE_URL', getenv('SYMFONY_DOTENV_VARS'));
// Special variable has a value
$_ENV['SYMFONY_DOTENV_VARS'] = 'APP_ENV';
$_SERVER['SYMFONY_DOTENV_VARS'] = 'APP_ENV';
putenv('SYMFONY_DOTENV_VARS=APP_ENV');
$_ENV['APP_DEBUG'] = '1';
$_SERVER['APP_DEBUG'] = '1';
putenv('APP_DEBUG=1');
unset($_ENV['DATABASE_URL']);
unset($_SERVER['DATABASE_URL']);
putenv('DATABASE_URL');
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['APP_DEBUG' => '0', 'DATABASE_URL' => 'mysql://root@localhost/db']);
$dotenv->populate(['DATABASE_URL' => 'sqlite:///somedb.sqlite']);
$this->assertSame('APP_ENV,DATABASE_URL', getenv('SYMFONY_DOTENV_VARS'));
}
public function testOverridingEnvVarsWithNamesMemorizedInSpecialVar()
{
putenv('SYMFONY_DOTENV_VARS='.$_SERVER['SYMFONY_DOTENV_VARS'] = 'FOO,BAR,BAZ');
putenv('FOO=foo');
putenv('BAR=bar');
putenv('BAZ=baz');
putenv('DOCUMENT_ROOT=/var/www');
$dotenv = (new Dotenv())->usePutenv();
$dotenv->populate(['FOO' => 'foo1', 'BAR' => 'bar1', 'BAZ' => 'baz1', 'DOCUMENT_ROOT' => '/boot']);
$this->assertSame('foo1', getenv('FOO'));
$this->assertSame('bar1', getenv('BAR'));
$this->assertSame('baz1', getenv('BAZ'));
$this->assertSame('/var/www', getenv('DOCUMENT_ROOT'));
}
public function testGetVariablesValueFromEnvFirst()
{
$_ENV['APP_ENV'] = 'prod';
$dotenv = new Dotenv();
$test = "APP_ENV=dev\nTEST1=foo1_\${APP_ENV}";
$values = $dotenv->parse($test);
$this->assertSame('foo1_prod', $values['TEST1']);
if ('\\' !== \DIRECTORY_SEPARATOR) {
$test = "APP_ENV=dev\nTEST2=foo2_\$(php -r 'echo \$_SERVER[\"APP_ENV\"];')";
$values = $dotenv->parse($test);
$this->assertSame('foo2_prod', $values['TEST2']);
}
}
public function testGetVariablesValueFromGetenv()
{
putenv('Foo=Bar');
$dotenv = new Dotenv();
try {
$values = $dotenv->parse('Foo=${Foo}');
$this->assertSame('Bar', $values['Foo']);
} finally {
putenv('Foo');
}
}
public function testNoDeprecationWarning()
{
$dotenv = new Dotenv();
$this->assertInstanceOf(Dotenv::class, $dotenv);
}
public function testDoNotUsePutenv()
{
$dotenv = new Dotenv();
$dotenv->populate(['TEST_USE_PUTENV' => 'no']);
$this->assertSame('no', $_SERVER['TEST_USE_PUTENV']);
$this->assertSame('no', $_ENV['TEST_USE_PUTENV']);
$this->assertFalse(getenv('TEST_USE_PUTENV'));
}
public function testBootEnv()
{
@mkdir($tmpdir = sys_get_temp_dir().'/dotenv');
$path = tempnam($tmpdir, 'sf-');
file_put_contents($path, 'FOO=BAR');
(new Dotenv('TEST_APP_ENV', 'TEST_APP_DEBUG'))->bootEnv($path);
$this->assertSame('BAR', $_SERVER['FOO']);
unset($_SERVER['FOO'], $_ENV['FOO']);
unlink($path);
file_put_contents($path.'.local.php', '<?php return ["TEST_APP_ENV" => "dev", "FOO" => "BAR"];');
(new Dotenv('TEST_APP_ENV', 'TEST_APP_DEBUG'))->bootEnv($path);
$this->assertSame('BAR', $_SERVER['FOO']);
$this->assertSame('1', $_SERVER['TEST_APP_DEBUG']);
unset($_SERVER['FOO'], $_ENV['FOO']);
unlink($path.'.local.php');
rmdir($tmpdir);
}
}