|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DevCoder; |
| 4 | + |
| 5 | +class DotEnv |
| 6 | +{ |
| 7 | + /** |
| 8 | + * The directory where the .env file can be located. |
| 9 | + * |
| 10 | + * @var string |
| 11 | + */ |
| 12 | + protected $path; |
| 13 | + |
| 14 | + |
| 15 | + public function __construct(string $path) |
| 16 | + { |
| 17 | + if(!file_exists($path)) { |
| 18 | + throw new \InvalidArgumentException(sprintf('%s does not exist', $path)); |
| 19 | + } |
| 20 | + $this->path = $path; |
| 21 | + } |
| 22 | + |
| 23 | + public function load() :void |
| 24 | + { |
| 25 | + if (!is_readable($this->path)) { |
| 26 | + throw new \InvalidArgumentException(sprintf('%s file is not readable', $this->path)); |
| 27 | + } |
| 28 | + |
| 29 | + $lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
| 30 | + foreach ($lines as $line) { |
| 31 | + |
| 32 | + if (strpos(trim($line), '#') === 0) { |
| 33 | + continue; |
| 34 | + } |
| 35 | + |
| 36 | + list($name, $value) = explode('=', $line, 2); |
| 37 | + $name = trim($name); |
| 38 | + $value = trim($value); |
| 39 | + |
| 40 | + if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) { |
| 41 | + putenv(sprintf('%s=%s', $name, $value)); |
| 42 | + $_ENV[$name] = $value; |
| 43 | + $_SERVER[$name] = $value; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments