1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Lib\Env; |
4
|
|
|
|
5
|
|
|
use Lib\Env\Exception\EnvException; |
6
|
|
|
use Lib\Env\Exception\PathException; |
7
|
|
|
use Lib\Env\Parser\EnvParserInterface; |
8
|
|
|
|
9
|
|
|
final class EnvVarsSetter |
10
|
|
|
{ |
11
|
|
|
private const DIST_EXT = '.dist'; |
12
|
|
|
|
13
|
|
|
private const ENV_DEV = 'dev'; |
14
|
|
|
private const ENV_TEST = 'test'; |
15
|
|
|
private const ENV_PROD = 'prod'; |
16
|
|
|
|
17
|
|
|
/** @var array */ |
18
|
|
|
private $envVars; |
19
|
|
|
|
20
|
|
|
/** @var EnvParserInterface */ |
21
|
|
|
private $parser; |
22
|
|
|
|
23
|
|
|
public function __construct(EnvParserInterface $parser) |
24
|
|
|
{ |
25
|
|
|
$this->parser = $parser; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $path |
30
|
|
|
* @param string $envVarName |
31
|
|
|
* @param string $defaultEnv |
32
|
|
|
* @param array $testEnvs |
33
|
|
|
* @throws EnvException |
34
|
|
|
*/ |
35
|
|
|
public function loadEnv(string $path, string $envVarName = 'APP_ENV', string $defaultEnv = 'dev', $testEnvs = ['test']): void |
36
|
|
|
{ |
37
|
|
|
if (null === $env = $_SERVER[$envVarName] ?? $_ENV[$envVarName] ?? null) { |
38
|
|
|
$this->envVars[$envVarName] = $env = $defaultEnv; |
39
|
|
|
} |
40
|
|
|
if (file_exists($path) && !file_exists($file = "$path.dist")) { |
41
|
|
|
$this->doLoad($path); |
42
|
|
|
} else { |
43
|
|
|
$this->doLoad($file); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (!\in_array($env, $testEnvs, true) && file_exists($file = "$path.local")) { |
47
|
|
|
$this->doLoad($file); |
48
|
|
|
} |
49
|
|
|
if (file_exists($file = "$path.$env")) { |
50
|
|
|
$this->doLoad($file); |
51
|
|
|
} |
52
|
|
|
if (file_exists($file = "$path.$env.local")) { |
53
|
|
|
$this->doLoad($file); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param string $path |
59
|
|
|
* @return string |
60
|
|
|
* @throws EnvException |
61
|
|
|
*/ |
62
|
|
|
public function doLoad(string $path): string |
63
|
|
|
{ |
64
|
|
|
if (!is_readable($path) || is_dir($path)) { |
65
|
|
|
throw new PathException(); |
66
|
|
|
} |
67
|
|
|
try { |
68
|
|
|
$this->populate($path); |
|
|
|
|
69
|
|
|
} catch (EnvException $e) { |
70
|
|
|
throw $e; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
private function populate(string $path, bool $override = false): void |
75
|
|
|
{ |
76
|
|
|
$vars = $this->parser->parse(file_get_contents($path)); |
77
|
|
|
foreach ($vars as $varName => $value) { |
78
|
|
|
$httpVar = 0 !== strpos($varName, 'HTTP_'); |
79
|
|
|
|
80
|
|
|
if (!$override && (isset($_ENV[$varName]) || ($httpVar && isset($_SERVER[$varName])))) { |
81
|
|
|
continue; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
putenv("$varName=$value"); |
85
|
|
|
$this->envVars[$varName] = $_ENV[$varName] = $value; |
86
|
|
|
if ($httpVar) { |
87
|
|
|
$_SERVER[$varName] = $value; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|