| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCommunity\Framework\Support; |
| 4 |
|
| 5 |
use RuntimeException; |
| 6 |
|
| 7 |
class Env |
| 8 |
{ |
| 9 |
protected static $localStore = []; |
| 10 |
|
| 11 |
/** |
| 12 |
* Load environment variables from a file. |
| 13 |
*/ |
| 14 |
public static function load(string $filePath): void |
| 15 |
{ |
| 16 |
if (!file_exists($filePath)) { |
| 17 |
throw new RuntimeException( |
| 18 |
"Environment file not found at: $filePath" |
| 19 |
); |
| 20 |
} |
| 21 |
|
| 22 |
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
| 23 |
|
| 24 |
foreach ($lines as $line) { |
| 25 |
$line = trim($line); |
| 26 |
|
| 27 |
if ($line === '' || strpos($line, '#') === 0) { |
| 28 |
continue; |
| 29 |
} |
| 30 |
|
| 31 |
[$name, $value] = array_pad(explode('=', $line, 2), 2, null); |
| 32 |
$name = trim($name); |
| 33 |
$value = trim((string) $value, "\"'"); |
| 34 |
|
| 35 |
if ($name === '') { |
| 36 |
continue; |
| 37 |
} |
| 38 |
|
| 39 |
static::set($name, static::normalize($value)); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Get an environment variable. |
| 45 |
*/ |
| 46 |
public static function get(string $key, $default = null) |
| 47 |
{ |
| 48 |
return array_key_exists($key, static::$localStore) |
| 49 |
? static::$localStore[$key] |
| 50 |
: $default; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Set an environment variable. |
| 55 |
*/ |
| 56 |
public static function set(string $key, $value): void |
| 57 |
{ |
| 58 |
static::$localStore[$key] = $value; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Get all environment variables. |
| 63 |
*/ |
| 64 |
public static function all(): array |
| 65 |
{ |
| 66 |
return static::$localStore; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Dump and die. |
| 71 |
*/ |
| 72 |
public static function dd(): void |
| 73 |
{ |
| 74 |
if (function_exists('dd')) { |
| 75 |
dd(static::all()); |
| 76 |
} else { |
| 77 |
print_r(static::all()); |
| 78 |
die; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Normalize string values to PHP native types. |
| 84 |
*/ |
| 85 |
protected static function normalize($value) |
| 86 |
{ |
| 87 |
if (!is_string($value)) { |
| 88 |
return $value; |
| 89 |
} |
| 90 |
|
| 91 |
$trimmed = strtolower(trim($value)); |
| 92 |
|
| 93 |
switch ($trimmed) { |
| 94 |
case 'true': |
| 95 |
case '(true)': |
| 96 |
case '1': |
| 97 |
return true; |
| 98 |
|
| 99 |
case 'false': |
| 100 |
case '(false)': |
| 101 |
case '0': |
| 102 |
return false; |
| 103 |
|
| 104 |
case 'null': |
| 105 |
case '(null)': |
| 106 |
return null; |
| 107 |
|
| 108 |
default: |
| 109 |
return $value; |
| 110 |
} |
| 111 |
} |
| 112 |
} |
| 113 |
|