luolongfei /
freenom
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * 环境变量 |
||
| 4 | * |
||
| 5 | * @author mybsdc <[email protected]> |
||
| 6 | * @date 2019/6/2 |
||
| 7 | * @time 17:28 |
||
| 8 | */ |
||
| 9 | |||
| 10 | namespace Luolongfei\Lib; |
||
| 11 | |||
| 12 | use Dotenv\Dotenv; |
||
| 13 | |||
| 14 | class Env |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @var Env |
||
| 18 | */ |
||
| 19 | protected static $instance; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var array 环境变量值 |
||
| 23 | */ |
||
| 24 | protected $allValues; |
||
| 25 | |||
| 26 | public function __construct($fileName) |
||
| 27 | { |
||
| 28 | $this->allValues = Dotenv::create(ROOT_PATH, $fileName)->load(); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 29 | } |
||
| 30 | |||
| 31 | public static function instance($fileName = '.env') |
||
| 32 | { |
||
| 33 | if (!self::$instance instanceof self) { |
||
| 34 | self::$instance = new self($fileName); |
||
| 35 | } |
||
| 36 | |||
| 37 | return self::$instance; |
||
| 38 | } |
||
| 39 | |||
| 40 | public function get($key = '', $default = null) |
||
| 41 | { |
||
| 42 | if (!strlen($key)) { // 不传key则返回所有环境变量 |
||
| 43 | return $this->allValues; |
||
| 44 | } |
||
| 45 | |||
| 46 | $value = getenv($key); |
||
| 47 | if ($value === false) { |
||
| 48 | return $default; |
||
| 49 | } |
||
| 50 | |||
| 51 | switch (strtolower($value)) { |
||
| 52 | case 'true': |
||
| 53 | case '(true)': |
||
| 54 | return true; |
||
| 55 | case 'false': |
||
| 56 | case '(false)': |
||
| 57 | return false; |
||
| 58 | case 'empty': |
||
| 59 | case '(empty)': |
||
| 60 | return ''; |
||
| 61 | case 'null': |
||
| 62 | case '(null)': |
||
| 63 | return null; |
||
| 64 | } |
||
| 65 | |||
| 66 | if (($valueLength = strlen($value)) > 1 && $value[0] === '"' && $value[$valueLength - 1] === '"') { // 去除双引号 |
||
| 67 | return substr($value, 1, -1); |
||
| 68 | } |
||
| 69 | |||
| 70 | return $value; |
||
| 71 | } |
||
| 72 | } |