|
21 | 21 | * Manages .env files.
|
22 | 22 | *
|
23 | 23 | * @author Fabien Potencier <[email protected]>
|
| 24 | + * @author Kévin Dunglas <[email protected]> |
24 | 25 | */
|
25 | 26 | final class Dotenv
|
26 | 27 | {
|
@@ -50,6 +51,32 @@ public function load(string $path, string ...$paths): void
|
50 | 51 | $this->doLoad(false, $path, $paths);
|
51 | 52 | }
|
52 | 53 |
|
| 54 | + /** |
| 55 | + * Loads one or several .env and the corresponding env.local, env.$env and env.$env.local files if they exist. |
| 56 | + * |
| 57 | + * The env.test.local is always ignored because tests should produce the same results for everyone. |
| 58 | + * |
| 59 | + * @param string $path A file to load |
| 60 | + * @param ...string $paths A list of additional files to load |
| 61 | + * |
| 62 | + * @throws FormatException when a file has a syntax error |
| 63 | + * @throws PathException when a file does not exist or is not readable |
| 64 | + * |
| 65 | + * @see https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use |
| 66 | + */ |
| 67 | + public function loadForEnv(string $env, string $path, string ...$paths): void |
| 68 | + { |
| 69 | + array_unshift($paths, $path); |
| 70 | + foreach ($paths as $p) { |
| 71 | + $pathList = ["$p.$env"]; |
| 72 | + if ($env !== 'test') { |
| 73 | + $pathList[] = "$p.local"; |
| 74 | + } |
| 75 | + $pathList[] = "$p.$env.local"; |
| 76 | + |
| 77 | + $this->doLoad(false, $p, $pathList, true); |
| 78 | + } |
| 79 | + } |
53 | 80 | /**
|
54 | 81 | * Loads one or several .env files and enables override existing vars.
|
55 | 82 | *
|
@@ -405,16 +432,24 @@ private function createFormatException($message)
|
405 | 432 | return new FormatException($message, new FormatExceptionContext($this->data, $this->path, $this->lineno, $this->cursor));
|
406 | 433 | }
|
407 | 434 |
|
408 |
| - private function doLoad(bool $overrideExistingVars, string $path, array $paths): void |
| 435 | + /** |
| 436 | + * @param bool $envMode Silently ignore not existing files in $paths (but not the one in $path) |
| 437 | + */ |
| 438 | + private function doLoad(bool $overrideExistingVars, string $path, array $paths, bool $envMode = false): void |
409 | 439 | {
|
410 | 440 | array_unshift($paths, $path);
|
411 | 441 |
|
| 442 | + $silent = false; |
412 | 443 | foreach ($paths as $path) {
|
413 | 444 | if (!is_readable($path) || is_dir($path)) {
|
| 445 | + if ($silent) { |
| 446 | + continue; |
| 447 | + } |
414 | 448 | throw new PathException($path);
|
415 | 449 | }
|
416 | 450 |
|
417 | 451 | $this->populate($this->parse(file_get_contents($path), $path), $overrideExistingVars);
|
| 452 | + $silent = $envMode; |
418 | 453 | }
|
419 | 454 | }
|
420 | 455 | }
|
0 commit comments