123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- namespace think;
- class Env
- {
-
- protected $data = [];
- public function __construct()
- {
- $this->data = $_ENV;
- }
-
- public function load($file)
- {
- $env = parse_ini_file($file, true);
- $this->set($env);
- }
-
- public function get($name = null, $default = null, $php_prefix = true)
- {
- if (is_null($name)) {
- return $this->data;
- }
- $name = strtoupper(str_replace('.', '_', $name));
- if (isset($this->data[$name])) {
- return $this->data[$name];
- }
- return $this->getEnv($name, $default, $php_prefix);
- }
- protected function getEnv($name, $default = null, $php_prefix = true)
- {
- if ($php_prefix) {
- $name = 'PHP_' . $name;
- }
- $result = getenv($name);
- if (false === $result) {
- return $default;
- }
- if ('false' === $result) {
- $result = false;
- } elseif ('true' === $result) {
- $result = true;
- }
- if (!isset($this->data[$name])) {
- $this->data[$name] = $result;
- }
- return $result;
- }
-
- public function set($env, $value = null)
- {
- if (is_array($env)) {
- $env = array_change_key_case($env, CASE_UPPER);
- foreach ($env as $key => $val) {
- if (is_array($val)) {
- foreach ($val as $k => $v) {
- $this->data[$key . '_' . strtoupper($k)] = $v;
- }
- } else {
- $this->data[$key] = $val;
- }
- }
- } else {
- $name = strtoupper(str_replace('.', '_', $env));
- $this->data[$name] = $value;
- }
- }
- }
|