Env.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Illuminate\Support;
  3. use Dotenv\Repository\Adapter\PutenvAdapter;
  4. use Dotenv\Repository\RepositoryBuilder;
  5. use PhpOption\Option;
  6. class Env
  7. {
  8. /**
  9. * Indicates if the putenv adapter is enabled.
  10. *
  11. * @var bool
  12. */
  13. protected static $putenv = true;
  14. /**
  15. * The environment repository instance.
  16. *
  17. * @var \Dotenv\Repository\RepositoryInterface|null
  18. */
  19. protected static $repository;
  20. /**
  21. * Enable the putenv adapter.
  22. *
  23. * @return void
  24. */
  25. public static function enablePutenv()
  26. {
  27. static::$putenv = true;
  28. static::$repository = null;
  29. }
  30. /**
  31. * Disable the putenv adapter.
  32. *
  33. * @return void
  34. */
  35. public static function disablePutenv()
  36. {
  37. static::$putenv = false;
  38. static::$repository = null;
  39. }
  40. /**
  41. * Get the environment repository instance.
  42. *
  43. * @return \Dotenv\Repository\RepositoryInterface
  44. */
  45. public static function getRepository()
  46. {
  47. if (static::$repository === null) {
  48. $builder = RepositoryBuilder::createWithDefaultAdapters();
  49. if (static::$putenv) {
  50. $builder = $builder->addAdapter(PutenvAdapter::class);
  51. }
  52. static::$repository = $builder->immutable()->make();
  53. }
  54. return static::$repository;
  55. }
  56. /**
  57. * Gets the value of an environment variable.
  58. *
  59. * @param string $key
  60. * @param mixed $default
  61. * @return mixed
  62. */
  63. public static function get($key, $default = null)
  64. {
  65. return Option::fromValue(static::getRepository()->get($key))
  66. ->map(function ($value) {
  67. switch (strtolower($value)) {
  68. case 'true':
  69. case '(true)':
  70. return true;
  71. case 'false':
  72. case '(false)':
  73. return false;
  74. case 'empty':
  75. case '(empty)':
  76. return '';
  77. case 'null':
  78. case '(null)':
  79. return;
  80. }
  81. if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
  82. return $matches[2];
  83. }
  84. return $value;
  85. })
  86. ->getOrCall(function () use ($default) {
  87. return value($default);
  88. });
  89. }
  90. }