-
Notifications
You must be signed in to change notification settings - Fork 1
/
EnvTrait.php
105 lines (93 loc) · 2.17 KB
/
EnvTrait.php
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
<?php
declare(strict_types=1);
namespace YourNamespace\App\Tests\Traits;
/**
* Trait EnvTrait.
*
* Trait for managing environment variables.
*
* @phpstan-ignore trait.unused
*/
trait EnvTrait {
/**
* The environment variables that were set.
*
* @var array
*/
protected static $env = [];
/**
* Set an environment variable.
*
* @param string $name
* The name of the environment variable.
* @param mixed $value
* The value of the environment variable.
*/
public static function envSet(string $name, mixed $value): void {
static::$env[$name] = $value;
putenv($name . '=' . $value);
}
/**
* Unset an environment variable.
*
* @param string $name
* The name of the environment variable.
*/
public static function envUnset(string $name): void {
unset(static::$env[$name]);
putenv($name);
}
/**
* Get an environment variable.
*
* @param string $name
* The name of the environment variable.
*/
public static function envGet(string $name): mixed {
return getenv($name);
}
/**
* Check if an environment variable is set.
*
* @param string $name
* The name of the environment variable.
*/
public static function envIsSet(string $name): bool {
return getenv($name) !== FALSE;
}
/**
* Check if an environment variable is not set.
*/
public static function envIsUnset($name): bool {
return getenv($name) === FALSE;
}
/**
* Reset environment variables.
*/
public static function envReset(): void {
foreach (array_keys(static::$env) as $name) {
static::envUnset($name);
}
static::$env = [];
}
/**
* Set environment variables from input.
*
* @param array $input
* The input array.
* @param string $prefix
* The prefix to look for.
* @param bool $remove
* Whether to remove the input variables.
*/
public static function envFromInput(array &$input, string $prefix, bool $remove = TRUE): void {
foreach ($input as $name => $value) {
if (str_starts_with($name, $prefix)) {
static::envSet($name, $value);
if ($remove) {
unset($input[$name]);
}
}
}
}
}