Env.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. class Env
  13. {
  14. /**
  15. * 环境变量数据
  16. * @var array
  17. */
  18. protected $data = [];
  19. public function __construct()
  20. {
  21. $this->data = $_ENV;
  22. }
  23. /**
  24. * 读取环境变量定义文件
  25. * @access public
  26. * @param string $file 环境变量定义文件
  27. * @return void
  28. */
  29. public function load($file)
  30. {
  31. $env = parse_ini_file($file, true);
  32. $this->set($env);
  33. }
  34. /**
  35. * 获取环境变量值
  36. * @access public
  37. * @param string $name 环境变量名
  38. * @param mixed $default 默认值
  39. * @return mixed
  40. */
  41. public function get($name = null, $default = null, $php_prefix = true)
  42. {
  43. if (is_null($name)) {
  44. return $this->data;
  45. }
  46. $name = strtoupper(str_replace('.', '_', $name));
  47. if (isset($this->data[$name])) {
  48. return $this->data[$name];
  49. }
  50. return $this->getEnv($name, $default, $php_prefix);
  51. }
  52. protected function getEnv($name, $default = null, $php_prefix = true)
  53. {
  54. if ($php_prefix) {
  55. $name = 'PHP_' . $name;
  56. }
  57. $result = getenv($name);
  58. if (false === $result) {
  59. return $default;
  60. }
  61. if ('false' === $result) {
  62. $result = false;
  63. } elseif ('true' === $result) {
  64. $result = true;
  65. }
  66. if (!isset($this->data[$name])) {
  67. $this->data[$name] = $result;
  68. }
  69. return $result;
  70. }
  71. /**
  72. * 设置环境变量值
  73. * @access public
  74. * @param string|array $env 环境变量
  75. * @param mixed $value 值
  76. * @return void
  77. */
  78. public function set($env, $value = null)
  79. {
  80. if (is_array($env)) {
  81. $env = array_change_key_case($env, CASE_UPPER);
  82. foreach ($env as $key => $val) {
  83. if (is_array($val)) {
  84. foreach ($val as $k => $v) {
  85. $this->data[$key . '_' . strtoupper($k)] = $v;
  86. }
  87. } else {
  88. $this->data[$key] = $val;
  89. }
  90. }
  91. } else {
  92. $name = strtoupper(str_replace('.', '_', $env));
  93. $this->data[$name] = $value;
  94. }
  95. }
  96. }