DotenvVariables.php
2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Dotenv\Environment;
use InvalidArgumentException;
/**
* The default implementation of the environment variables interface.
*/
class DotenvVariables extends AbstractVariables
{
/**
* The set of adapters to use.
*
* @var \Dotenv\Environment\Adapter\AdapterInterface[]
*/
protected $adapters;
/**
* Create a new dotenv environment variables instance.
*
* @param \Dotenv\Environment\Adapter\AdapterInterface[] $adapters
* @param bool $immutable
*
* @return void
*/
public function __construct(array $adapters, $immutable)
{
$this->adapters = $adapters;
parent::__construct($immutable);
}
/**
* Get an environment variable.
*
* We do this by querying our adapters sequentially.
*
* @param string $name
*
* @throws \InvalidArgumentException
*
* @return string|null
*/
public function get($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
}
foreach ($this->adapters as $adapter) {
$result = $adapter->get($name);
if ($result->isDefined()) {
return $result->get();
}
}
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function set($name, $value = null)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
}
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if ($this->isImmutable() && $this->get($name) !== null) {
return;
}
foreach ($this->adapters as $adapter) {
$adapter->set($name, $value);
}
}
/**
* Clear an environment variable.
*
* @param string $name
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function clear($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
}
// Don't clear anything if we're immutable.
if ($this->isImmutable()) {
return;
}
foreach ($this->adapters as $adapter) {
$adapter->clear($name);
}
}
}