@@ -47,33 +47,38 @@ final class Dotenv
47
47
*/
48
48
public function load (string $ path , string ...$ paths ): void
49
49
{
50
- array_unshift ($ paths , $ path );
51
-
52
- foreach ($ paths as $ path ) {
53
- if (!is_readable ($ path ) || is_dir ($ path )) {
54
- throw new PathException ($ path );
55
- }
50
+ $ this ->doLoad (false , $ path , ...$ paths );
51
+ }
56
52
57
- $ this ->populate ($ this ->parse (file_get_contents ($ path ), $ path ));
58
- }
53
+ /**
54
+ * Loads one or several .env files and enables override existing vars.
55
+ *
56
+ * @param string $path A file to load
57
+ * @param ...string $paths A list of additional files to load
58
+ *
59
+ * @throws FormatException when a file has a syntax error
60
+ * @throws PathException when a file does not exist or is not readable
61
+ */
62
+ public function overload (string $ path , string ...$ paths ): void
63
+ {
64
+ $ this ->doLoad (true , $ path , ...$ paths );
59
65
}
60
66
61
67
/**
62
68
* Sets values as environment variables (via putenv, $_ENV, and $_SERVER).
63
69
*
64
- * Note that existing environment variables are not overridden.
65
- *
66
- * @param array $values An array of env variables
70
+ * @param array $values An array of env variables
71
+ * @param bool $overrideExistingVars true when existing environment variables must be overridden
67
72
*/
68
- public function populate (array $ values ): void
73
+ public function populate (array $ values, bool $ overrideExistingVars = false ): void
69
74
{
70
75
$ loadedVars = array_flip (explode (', ' , getenv ('SYMFONY_DOTENV_VARS ' )));
71
76
unset($ loadedVars ['' ]);
72
77
73
78
foreach ($ values as $ name => $ value ) {
74
79
$ notHttpName = 0 !== strpos ($ name , 'HTTP_ ' );
75
80
// don't check existence with getenv() because of thread safety issues
76
- if (!isset ($ loadedVars [$ name ]) && (isset
8000
span>($ _ENV [$ name ]) || (isset ($ _SERVER [$ name ]) && $ notHttpName ))) {
81
+ if (!isset ($ loadedVars [$ name ]) && (! $ overrideExistingVars && ( isset ($ _ENV [$ name ]) || (isset ($ _SERVER [$ name ]) && $ notHttpName) ))) {
77
82
continue ;
78
83
}
79
84
@@ -399,4 +404,17 @@ private function createFormatException($message)
399
404
{
400
405
return new FormatException ($ message , new FormatExceptionContext ($ this ->data , $ this ->path , $ this ->lineno , $ this ->cursor ));
401
406
}
407
+
408
+ private function doLoad (bool $ overrideExistingVars , string $ path , string ...$ paths ): void
409
+ {
410
+ array_unshift ($ paths , $ path );
411
+
412
+ foreach ($ paths as $ path ) {
413
+ if (!is_readable ($ path ) || is_dir ($ path )) {
414
+ throw new PathException ($ path );
415
+ }
416
+
417
+ $ this ->populate ($ this ->parse (file_get_contents ($ path ), $ path ), $ overrideExistingVars );
418
+ }
419
+ }
402
420
}
0 commit comments