1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AbterPhp\Framework\Environments; |
6
|
|
|
|
7
|
|
|
use AbterPhp\Framework\Constant\Env; |
8
|
|
|
use Opulence\Environments\Environment as OpulenceEnvironment; |
9
|
|
|
|
10
|
|
|
class Environment extends OpulenceEnvironment |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Unsets an environment variable |
14
|
|
|
* |
15
|
|
|
* @param string $name The name of the environment variable to unset |
16
|
|
|
*/ |
17
|
|
|
public static function unsetVar(string $name): void |
18
|
|
|
{ |
19
|
|
|
putenv("$name"); |
20
|
|
|
if (array_key_exists($name, $_ENV)) { |
21
|
|
|
unset($_ENV[$name]); |
22
|
|
|
} |
23
|
|
|
if (array_key_exists($name, $_SERVER)) { |
24
|
|
|
unset($_SERVER[$name]); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Gets the value of an environment variable |
30
|
|
|
* Throws a runtime exception instead of returning null |
31
|
|
|
* |
32
|
|
|
* @param string $name The name of the environment variable to get |
33
|
|
|
* @param string $default The default value if none existed |
34
|
|
|
* @return string The value of the environment value if one was set, value of default otherwise |
35
|
|
|
*/ |
36
|
|
|
public static function mustGetVar(string $name, string $default = ""): string |
37
|
|
|
{ |
38
|
|
|
$value = parent::getVar($name, $default); |
39
|
|
|
|
40
|
|
|
if (!$value) { |
41
|
|
|
throw new \RuntimeException("missing environment variable: " . $name); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $value; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Sets an environment variable, but does not overwrite existing variables |
49
|
|
|
* |
50
|
|
|
* @param string $name The name of the environment variable to set |
51
|
|
|
* @param mixed $value The value |
52
|
|
|
*/ |
53
|
|
|
public static function setVar(string $name, $value) |
54
|
|
|
{ |
55
|
|
|
putenv("$name=$value"); |
56
|
|
|
$_ENV[$name] = $value; |
57
|
|
|
$_SERVER[$name] = $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @return bool |
62
|
|
|
*/ |
63
|
|
|
public static function isStaging(): bool |
64
|
|
|
{ |
65
|
|
|
return static::mustGetVar(Env::ENV_NAME) === Environment::STAGING; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return bool |
70
|
|
|
*/ |
71
|
|
|
public static function isTesting(): bool |
72
|
|
|
{ |
73
|
|
|
return static::mustGetVar(Env::ENV_NAME) === Environment::TESTING; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return bool |
78
|
|
|
*/ |
79
|
|
|
public static function isDevelopment(): bool |
80
|
|
|
{ |
81
|
|
|
return static::mustGetVar(Env::ENV_NAME) === Environment::DEVELOPMENT; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @return bool |
86
|
|
|
*/ |
87
|
|
|
public static function isProduction(): bool |
88
|
|
|
{ |
89
|
|
|
return static::getVar(Env::ENV_NAME) === Environment::PRODUCTION; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|