bug #29171 [Dotenv] load .env.dist when it exists and .env is not found (nicolas-grekas)

This PR was merged into the 4.2-dev branch.

Discussion
----------

[Dotenv] load .env.dist when it exists and .env is not found

| Q             | A
| ------------- | ---
| Branch?       | 4.2
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #29170
| License       | MIT
| Doc PR        | -

As illustrated in #29170, it can be useful to opt out from the `.env` convention and fall back to defining env vars in `.env.dist` instead. This PR allows that by loading `.env.dist` when it exists and `.env` is not found.

Needs https://github.com/symfony/flex/pull/434 to work seamlessly when using Flex.

Commits
-------

841185bb9f [Dotenv] load .env.dist when it exists and .env is not found
This commit is contained in:
Nicolas Grekas 2018-11-12 10:14:20 +01:00
commit e9470431d2
3 changed files with 16 additions and 3 deletions

View File

@ -5,6 +5,7 @@ CHANGELOG
-----
* added `Dotenv::overload()` and `$overrideExistingVars` as optional parameter of `Dotenv::populate()`
* added `Dotenv::loadEnv()` to load a .env file and its corresponding .env.local, .env.$env and .env.$env.local files if they exist
3.3.0
-----

View File

@ -55,6 +55,7 @@ final class Dotenv
* 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 $varName The name of the env vars that defines the app env
@ -66,7 +67,11 @@ final class Dotenv
*/
public function loadEnv(string $path, string $varName = 'APP_ENV', string $defaultEnv = 'dev', array $testEnvs = array('test')): void
{
$this->load($path);
if (file_exists($path) || !file_exists($p = "$path.dist")) {
$this->load($path);
} else {
$this->load($p);
}
if (null === $env = $_SERVER[$varName] ?? $_ENV[$varName] ?? null) {
$this->populate(array($varName => $env = $defaultEnv));

View File

@ -231,11 +231,18 @@ class DotenvTest extends TestCase
(new DotEnv())->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('devlocalBAR', getenv('FOO'));
// .env.dist
unlink($path);
file_put_contents("$path.dist", 'BAR=distBAR');
(new DotEnv())->loadEnv($path, 'TEST_APP_ENV');
$this->assertSame('distBAR', getenv('BAR'));
putenv('FOO');
putenv('BAR');
unlink($path);
unlink("$path.dev");
unlink("$path.dist");
unlink("$path.local");
unlink("$path.dev");
unlink("$path.dev.local");
rmdir($tmpdir);
}