1: <?php
2:
3: namespace Chromabits\Nucleus\Support;
4:
5: use Chromabits\Nucleus\Control\Maybe;
6: use Chromabits\Nucleus\Data\ArrayMap;
7: use Chromabits\Nucleus\Exceptions\CoreException;
8: use Chromabits\Nucleus\Foundation\StaticObject;
9:
10: 11: 12: 13: 14: 15: 16: 17:
18: class Env extends StaticObject
19: {
20: 21: 22: 23: 24: 25: 26: 27:
28: public static function get($key, $default = null)
29: {
30: $value = static::getRaw($key, $default);
31:
32: if (is_string($value)) {
33:
34: switch (strtolower($value)) {
35: case 'true':
36: return true;
37:
38: case 'false':
39: return false;
40:
41: case 'null':
42: return null;
43: }
44:
45:
46: if (Str::beginsWith($value, '"') && Str::endsWith($value, '"')) {
47: return substr($value, 1, -1);
48: }
49: }
50:
51: return $value;
52: }
53:
54: 55: 56: 57: 58: 59: 60: 61: 62: 63:
64: public static function getRaw($key, $default = null)
65: {
66: $env = ArrayMap::of($_ENV);
67: $server = ArrayMap::of($_SERVER);
68:
69: if ($env->member($key)) {
70: return Maybe::fromJust($env->lookup($key));
71: } elseif ($server->member($key)) {
72: return Maybe::fromJust($server->lookup($key));
73: }
74:
75: $value = getenv($key);
76:
77: if ($value === false) {
78: return Std::thunk($default);
79: }
80:
81: return $value;
82: }
83:
84: 85: 86: 87: 88: 89: 90:
91: public static function getOrFail($key)
92: {
93: return static::get($key, function () use ($key) {
94: throw new CoreException(vsprintf(
95: 'The variable %s was not found in the environment',
96: [$key]
97: ));
98: });
99: }
100:
101: 102: 103: 104: 105: 106:
107: public static function set($key, $value)
108: {
109: putenv(vsprintf('%s=%s', [$key, $value]));
110: $_ENV[$key] = $value;
111: $_SERVER[$key] = $value;
112: }
113: }
114: