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

This commit is contained in:
Nicolas Grekas 2018-11-11 10:03:32 +01:00
parent a4204cd685
commit 841185bb9f
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);
}