DotenvManager.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Support;
  12. use Dotenv\Dotenv;
  13. use Dotenv\Repository\Adapter\AdapterInterface;
  14. use Dotenv\Repository\Adapter\PutenvAdapter;
  15. use Dotenv\Repository\RepositoryBuilder;
  16. class DotenvManager
  17. {
  18. protected static AdapterInterface $adapter;
  19. protected static Dotenv $dotenv;
  20. protected static array $cachedValues;
  21. public static function load(array $paths): void
  22. {
  23. if (isset(static::$cachedValues)) {
  24. return;
  25. }
  26. static::$cachedValues = static::getDotenv($paths)->load();
  27. }
  28. public static function reload(array $paths, bool $force = false): void
  29. {
  30. if (! isset(static::$cachedValues)) {
  31. static::load($paths);
  32. return;
  33. }
  34. foreach (static::$cachedValues as $deletedEntry => $value) {
  35. static::getAdapter()->delete($deletedEntry);
  36. }
  37. static::$cachedValues = static::getDotenv($paths, $force)->load();
  38. }
  39. protected static function getDotenv(array $paths, bool $force = false): Dotenv
  40. {
  41. if (isset(static::$dotenv) && ! $force) {
  42. return static::$dotenv;
  43. }
  44. return static::$dotenv = Dotenv::create(
  45. RepositoryBuilder::createWithNoAdapters()
  46. ->addAdapter(static::getAdapter($force))
  47. ->immutable()
  48. ->make(),
  49. $paths
  50. );
  51. }
  52. protected static function getAdapter(bool $force = false): AdapterInterface
  53. {
  54. if (isset(static::$adapter) && ! $force) {
  55. return static::$adapter;
  56. }
  57. return static::$adapter = PutenvAdapter::create()->get();
  58. }
  59. }