10000 [Dotenv] load .env.dist when it exists and .env is not found · symfony/symfony@841185b · GitHub
[go: up one dir, main page]

Skip to content

Commit 841185b

Browse files
[Dotenv] load .env.dist when it exists and .env is not found
1 parent a4204cd commit 841185b

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

src/Symfony/Component/Dotenv/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
-----
66

77
* added `Dotenv::overload()` and `$overrideExistingVars` as optional parameter of `Dotenv::populate()`
8+
* added `Dotenv::loadEnv()` to load a .env file and its corresponding .env.local, .env.$env and .env.$env.local files if they exist
89

910
3.3.0
1011
-----

src/Symfony/Component/Dotenv/Dotenv.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ public function load(string $path, string ...$extraPaths): void
5555
* Loads a .env file and the corresponding .env.local, .env.$env and .env.$env.local files if they exist.
5656
*
5757
* .env.local is always ignored in test env because tests should produce the same results for everyone.
58+
* .env.dist is loaded when it exists and .env is not found.
5859
*
5960
* @param string $path A file to load
6061
* @param string $varName The name of the env vars that defines the app env
@@ -66,7 +67,11 @@ public function load(string $path, string ...$extraPaths): void
6667
*/
6768
public function loadEnv(string $path, string $varName = 'APP_ENV', string $defaultEnv = 'dev', array $testEnvs = array('test')): void
6869
{
69-
$this->load($path);
70+
if (file_exists($path) || !file_exists($p = "$path.dist")) {
71+
$this->load($path);
72+
} else {
73+
$this->load($p);
74+
}
7075

7176
if (null === $env = $_SERVER[$varName] ?? $_ENV[$varName] ?? null) {
7277
$this->populate(array($varName => $env = $defaultEnv));

src/Symfony/Component/Dotenv/Tests/DotenvTest.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -231,11 +231,18 @@ public function testLoadEnv()
231231
(new DotEnv())->loadEnv($path, 'TEST_APP_ENV');
232232
$this->assertSame('devlocalBAR', getenv('FOO'));
233233

234+
// .env.dist
235+
236+
unlink($path);
237+
file_put_contents("$path.dist", 'BAR=distBAR');
238+
(new DotEnv())->loadEnv($path, 'TEST_APP_ENV');
239+
$this->assertSame('distBAR', getenv('BAR'));
240+
234241
putenv('FOO');
235242
putenv('BAR');
236-
unlink($path);
237-
unlink("$path.dev");
243+
unlink("$path.dist");
238244
unlink("$path.local");
245+
unlink("$path.dev");
239246
unlink("$path.dev.local");
240247
rmdir($tmpdir);
241248
}

0 commit comments

Comments
 (0)
0