|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Config; |
| 4 | + |
| 5 | +/** |
| 6 | + * Lightweight .env loader for PHP-CRUD-API-Generator. |
| 7 | + * |
| 8 | + * This avoids adding external dependencies while still allowing |
| 9 | + * configuration via environment variables or a project-level .env file. |
| 10 | + */ |
| 11 | +class Env |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Load key=value pairs from a .env-style file into getenv()/$_ENV/$_SERVER. |
| 15 | + */ |
| 16 | + public static function load(string $path): void |
| 17 | + { |
| 18 | + if (!is_file($path) || !is_readable($path)) { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
| 23 | + if ($lines === false) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + foreach ($lines as $line) { |
| 28 | + $line = trim($line); |
| 29 | + |
| 30 | + // Skip comments and empty lines |
| 31 | + if ($line === '' || $line[0] === '#' || $line[0] === ';') { |
| 32 | + continue; |
| 33 | + } |
| 34 | + |
| 35 | + $parts = explode('=', $line, 2); |
| 36 | + if (count($parts) !== 2) { |
| 37 | + continue; |
| 38 | + } |
| 39 | + |
| 40 | + $name = trim($parts[0]); |
| 41 | + $value = trim($parts[1]); |
| 42 | + |
| 43 | + if ($name === '') { |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + // Strip simple surrounding quotes |
| 48 | + if ($value !== '' && ($value[0] === '"' || $value[0] === "'")) { |
| 49 | + $quote = $value[0]; |
| 50 | + if (substr($value, -1) === $quote) { |
| 51 | + $value = substr($value, 1, -1); |
| 52 | + } else { |
| 53 | + $value = substr($value, 1); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // Do not override explicitly set environment variables |
| 58 | + if (getenv($name) === false) { |
| 59 | + putenv($name . '=' . $value); |
| 60 | + } |
| 61 | + |
| 62 | + if (!array_key_exists($name, $_ENV)) { |
| 63 | + $_ENV[$name] = $value; |
| 64 | + } |
| 65 | + |
| 66 | + if (!array_key_exists($name, $_SERVER)) { |
| 67 | + $_SERVER[$name] = $value; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments