| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Loads an environment variable |
| 5 | * |
| 6 | * @param string $name |
| 7 | * @param mixed|null $def |
| 8 | * @param bool $local |
| 9 | * @return array|mixed|string|null |
| 10 | */ |
| 11 | function env(string $name, $def = null, bool $local = false) { |
| 12 | $value = getenv($name, $local); |
| 13 | if ($value) { |
| 14 | return parse_raw_value($value); |
| 15 | } |
| 16 | return $def; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Parses and filters values coming from environment or shell variables. |
| 21 | * |
| 22 | * @param $value |
| 23 | * @return bool|mixed|string|void |
| 24 | */ |
| 25 | function parse_raw_value($value) { |
| 26 | $value = trim($value); |
| 27 | |
| 28 | switch (strtolower($value)) { |
| 29 | case 'true': |
| 30 | case '(true)': |
| 31 | return true; |
| 32 | case 'false': |
| 33 | case '(false)': |
| 34 | return false; |
| 35 | case 'empty': |
| 36 | case '(empty)': |
| 37 | return ''; |
| 38 | case 'null': |
| 39 | case '(null)': |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | // If there are any pair of quotes around tbe value then we need to remove it |
| 44 | if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) { |
| 45 | return $matches[2]; |
| 46 | } |
| 47 | |
| 48 | return $value; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Loads a DotEnv file. |
| 53 | * |
| 54 | * @param string|null $path |
| 55 | * @param bool $optional |
| 56 | * @return array |
| 57 | */ |
| 58 | function load_dotenv_file(string $path = null, bool $optional = true): array { |
| 59 | $env = []; |
| 60 | |
| 61 | if (empty($path)) { |
| 62 | $path = getcwd().DIRECTORY_SEPARATOR.'.env'; |
| 63 | } |
| 64 | |
| 65 | if (!file_exists($path)) { |
| 66 | if ($optional) { |
| 67 | return $env; |
| 68 | } |
| 69 | throw new \InvalidArgumentException(sprintf('%s does not exist', $path)); |
| 70 | } |
| 71 | |
| 72 | if (!is_readable($path)) { |
| 73 | throw new \RuntimeException(sprintf('%s file is not readable', $path)); |
| 74 | } |
| 75 | |
| 76 | $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
| 77 | |
| 78 | foreach ($lines as $line) { |
| 79 | if (strpos(trim($line), '#') === 0) { |
| 80 | continue; |
| 81 | } |
| 82 | |
| 83 | list($name, $value) = explode('=', $line, 2); |
| 84 | $name = trim($name); |
| 85 | $value = trim($value, " \n\r\t\v\x00\""); |
| 86 | $value = parse_raw_value($value); |
| 87 | $env[$name] = $value; |
| 88 | } |
| 89 | |
| 90 | foreach ($env as $name => $value) { |
| 91 | putenv(sprintf('%s=%s', $name, $value)); |
| 92 | $_ENV[$name] = $value; |
| 93 | $_SERVER[$name] = $value; |
| 94 | } |
| 95 | |
| 96 | return $env; |
| 97 | } |
anthony / Simple dotenv loader
Last active 3 months ago
Taken from https://gist.github.com/shakahl/9933eb74b8a89d3e5f34c86ce1f0c840