1
|
|
|
<?php |
2
|
|
|
namespace Consolidation\Config\Util; |
3
|
|
|
|
4
|
|
|
use Consolidation\Config\Config; |
5
|
|
|
use Consolidation\Config\ConfigInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Provide a configuration object that fetches values from environment |
9
|
|
|
* variables. |
10
|
|
|
*/ |
11
|
|
|
class EnvConfig implements ConfigInterface |
12
|
|
|
{ |
13
|
|
|
/** @var string */ |
14
|
|
|
protected $prefix; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* EnvConfig constructor |
18
|
|
|
* |
19
|
|
|
* @param $prefix The string to appear before every environment |
20
|
|
|
* variable key. For example, if the prefix is 'MYAPP_', then |
21
|
|
|
* the key 'foo.bar' will be fetched from the environment variable |
22
|
|
|
* MYAPP_FOO_BAR. |
23
|
|
|
*/ |
24
|
|
|
public function __construct($prefix) |
25
|
|
|
{ |
26
|
|
|
// Ensure that the prefix is always uppercase, and always |
27
|
|
|
// ends with a '_', regardless of the form the caller provided. |
28
|
|
|
$this->prefix = strtoupper(rtrim($prefix, '_')) . '_'; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @inheritdoc |
33
|
|
|
*/ |
34
|
|
|
public function has($key) |
35
|
|
|
{ |
36
|
|
|
return $this->get($key) !== null; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @inheritdoc |
41
|
|
|
*/ |
42
|
|
|
public function get($key, $defaultFallback = null) |
43
|
|
|
{ |
44
|
|
|
$envKey = $this->prefix . strtoupper(strtr($key, '.-', '__')); |
45
|
|
|
$envKey = str_replace($this->prefix . $this->prefix, $this->prefix, $envKey); |
46
|
|
|
return getenv($envKey) ?: $defaultFallback; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @inheritdoc |
51
|
|
|
*/ |
52
|
|
|
public function set($key, $value) |
53
|
|
|
{ |
54
|
|
|
throw new \Exception('Cannot call "set" on environmental configuration.'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @inheritdoc |
59
|
|
|
*/ |
60
|
|
|
public function import($data) |
61
|
|
|
{ |
62
|
|
|
// no-op |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @inheritdoc |
67
|
|
|
*/ |
68
|
|
|
public function export() |
69
|
|
|
{ |
70
|
|
|
return []; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @inheritdoc |
75
|
|
|
*/ |
76
|
|
|
public function hasDefault($key) |
77
|
|
|
{ |
78
|
|
|
return false; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @inheritdoc |
83
|
|
|
*/ |
84
|
|
|
public function getDefault($key, $defaultFallback = null) |
85
|
|
|
{ |
86
|
|
|
return $defaultFallback; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @inheritdoc |
91
|
|
|
*/ |
92
|
|
|
public function setDefault($key, $value) |
93
|
|
|
{ |
94
|
|
|
throw new \Exception('Cannot call "setDefault" on environmental configuration.'); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|