1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace DL\ConsulPhpEnvVar\Service; |
5
|
|
|
|
6
|
|
|
use SensioLabs\Consul\Services\KV; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Manages environment variables through Consul. |
10
|
|
|
* |
11
|
|
|
* @package DL\ConsulPhpEnvVar\Service |
12
|
|
|
* @author Petre Pătrașc <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class ConsulEnvManager |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var KV |
18
|
|
|
*/ |
19
|
|
|
protected $kv; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var bool |
23
|
|
|
*/ |
24
|
|
|
protected $overwriteEvenIfDefined = false; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* ConsulEnvManager constructor. |
28
|
|
|
* |
29
|
|
|
* @param KV $kv |
30
|
|
|
* @param bool $overwriteEvenIfDefined |
31
|
|
|
*/ |
32
|
7 |
|
public function __construct(KV $kv, bool $overwriteEvenIfDefined = false) |
33
|
|
|
{ |
34
|
7 |
|
$this->kv = $kv; |
35
|
7 |
|
$this->overwriteEvenIfDefined = $overwriteEvenIfDefined; |
36
|
7 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Add missing environment variables from Consul. |
40
|
|
|
* |
41
|
|
|
* @param array $mappings |
42
|
|
|
*/ |
43
|
3 |
|
public function getEnvVarsFromConsul(array $mappings) |
44
|
|
|
{ |
45
|
3 |
|
foreach ($mappings as $environmentKey => $kvPath) { |
46
|
3 |
|
$keyExists = $this->keyIsDefined($environmentKey); |
47
|
3 |
|
if ($keyExists && !$this->overwriteEvenIfDefined) { |
48
|
1 |
|
continue; |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
$consulValue = $this->getKeyValueFromConsul($kvPath); |
52
|
2 |
|
$this->saveKeyValueInEnvironmentVars($environmentKey, $consulValue); |
53
|
|
|
} |
54
|
3 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Check if an environment key is defined. |
58
|
|
|
* |
59
|
|
|
* @param string $environmentKey |
60
|
|
|
* |
61
|
|
|
* @return bool |
62
|
|
|
*/ |
63
|
3 |
|
private function keyIsDefined(string $environmentKey): bool |
64
|
|
|
{ |
65
|
3 |
|
$keyValue = getenv($environmentKey); |
66
|
|
|
|
67
|
3 |
|
if (false === $keyValue) { |
68
|
1 |
|
return false; |
69
|
|
|
} |
70
|
|
|
|
71
|
2 |
|
return true; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Get a key value from Consul. |
76
|
|
|
* |
77
|
|
|
* @param string $kvPath |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
2 |
|
private function getKeyValueFromConsul(string $kvPath): string |
82
|
|
|
{ |
83
|
2 |
|
return $this->kv->get($kvPath)->getBody(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Save the value of a key in an environment variable. |
88
|
|
|
* |
89
|
|
|
* @param string $envKey |
90
|
|
|
* @param string $kvValue |
91
|
|
|
*/ |
92
|
2 |
|
private function saveKeyValueInEnvironmentVars($envKey, $kvValue) |
93
|
|
|
{ |
94
|
2 |
|
putenv("{$envKey}={$kvValue}"); |
95
|
2 |
|
} |
96
|
|
|
} |
97
|
|
|
|