diff --git a/composer.json b/composer.json index 2bf808f..5626dfc 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,10 @@ "email": "huangdijia@gmail.com" } ], + "support": { + "issues": "https://github.com/friendsofhyperf/components/issues", + "source": "https://github.com/friendsofhyperf/components" + }, "require": { "hyperf/di": "~3.0.0", "hyperf/collection": "~3.0.0", @@ -35,15 +39,12 @@ } }, "suggest": { - "hyperf/async-queue": "Required to use Hyperf\\AsyncQueue\\Job.(~3.0.0)" + "hyperf/async-queue": "Required to use Hyperf\\AsyncQueue\\Job.(~3.0.0)", + "vlucas/phpdotenv": "Required to use Dotenv.(^5.0)" }, "minimum-stability": "dev", "config": { "sort-packages": true, "optimize-autoloader": true - }, - "support": { - "issues": "https://github.com/friendsofhyperf/components/issues", - "source": "https://github.com/friendsofhyperf/components" } } diff --git a/src/Env.php b/src/Env.php new file mode 100644 index 0000000..884a553 --- /dev/null +++ b/src/Env.php @@ -0,0 +1,132 @@ +addAdapter(PutenvAdapter::class); + } + + static::$repository = $builder->immutable()->make(); + } + + return static::$repository; + } + + /** + * Get the value of an environment variable. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public static function get($key, $default = null) + { + return self::getOption($key)->getOrCall(fn () => value($default)); + } + + /** + * Get the value of a required environment variable. + * + * @param string $key + * @return mixed + * + * @throws RuntimeException + */ + public static function getOrFail($key) + { + return self::getOption($key)->getOrThrow(new RuntimeException("Environment variable [{$key}] has no value.")); + } + + /** + * Get the possible option for this environment variable. + * + * @param string $key + * @return \PhpOption\Option|\PhpOption\Some + */ + protected static function getOption($key) + { + return Option::fromValue(static::getRepository()->get($key)) + ->map(function ($value) { + switch (strtolower($value)) { + case 'true': + case '(true)': + return true; + case 'false': + case '(false)': + return false; + case 'empty': + case '(empty)': + return ''; + case 'null': + case '(null)': + return; + } + + if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) { + return $matches[2]; + } + + return $value; + }); + } +}