dotenv.php 1.1 KB

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