Env.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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)
  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);
  51. }
  52. protected function getEnv($name, $default = null)
  53. {
  54. $result = getenv('PHP_' . $name);
  55. if (false !== $result) {
  56. if ('false' === $result) {
  57. $result = false;
  58. } elseif ('true' === $result) {
  59. $result = true;
  60. }
  61. if (!isset($this->data[$name])) {
  62. $this->data[$name] = $result;
  63. }
  64. return $result;
  65. } else {
  66. return $default;
  67. }
  68. }
  69. /**
  70. * 设置环境变量值
  71. * @access public
  72. * @param string|array $env 环境变量
  73. * @param mixed $value 值
  74. * @return void
  75. */
  76. public function set($env, $value = null)
  77. {
  78. if (is_array($env)) {
  79. $env = array_change_key_case($env, CASE_UPPER);
  80. foreach ($env as $key => $val) {
  81. if (is_array($val)) {
  82. foreach ($val as $k => $v) {
  83. $this->data[$key . '_' . strtoupper($k)] = $v;
  84. }
  85. } else {
  86. $this->data[$key] = $val;
  87. }
  88. }
  89. } else {
  90. $name = strtoupper(str_replace('.', '_', $env));
  91. $this->data[$name] = $value;
  92. }
  93. }
  94. }