File tree Expand file tree Collapse file tree 2 files changed +87
-0
lines changed Expand file tree Collapse file tree 2 files changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+ /**
5+ * This file is part of Simps.
6+ *
7+ * @link https://simps.io
8+ * @document https://doc.simps.io
9+ * @license https://github.com/simple-swoole/simps/blob/master/LICENSE
10+ */
11+ namespace Simps \Utils ;
12+
13+ class Env
14+ {
15+ protected $ env ;
16+
17+ /**
18+ * 加载配置文件.
19+ */
20+ public function __construct ()
21+ {
22+ $ str = @file_get_contents (BASE_PATH . '/.env ' );
23+ $ arr = explode ("\n" , $ str );
24+ foreach ($ arr as $ v ) {
25+ $ v = $ this ->parse ($ v );
26+ if ($ v ) {
27+ $ this ->env [$ v [0 ]] = $ v [1 ];
28+ }
29+ }
30+ }
31+
32+ /**
33+ * 获取环境变量.
34+ * @param $key
35+ * @param null $default
36+ * @return null|mixed
37+ */
38+ public function get ($ key , $ default = null )
39+ {
40+ return $ this ->env [$ key ] ?? $ default ;
41+ }
42+
43+ /**
44+ * 解析加载项.
45+ * @param $str
46+ * @return null|array
47+ */
48+ protected function parse ($ str )
49+ {
50+ $ r = strpos ($ str , '= ' );
51+ if (! $ r ) {
52+ return null ;
53+ }
54+ $ key = trim (substr ($ str , 0 , $ r ));
55+ if (! $ key ) {
56+ return null ;
57+ }
58+ $ j = strpos ($ str , '# ' );
59+ if ($ j === false ) {
60+ $ val = trim (substr ($ str , $ r + 1 ));
61+ } else {
62+ $ val = trim (substr ($ str , $ r + 1 , $ j - $ r - 1 ));
63+ }
64+ switch ($ val ) {
65+ case 'true ' :
66+ case '(true) ' :
67+ return [$ key , true ];
68+ case 'false ' :
69+ case '(false) ' :
70+ return [$ key , false ];
71+ case 'empty ' :
72+ case '(empty) ' :
73+ return [$ key , '' ];
74+ case 'null ' :
75+ case '(null) ' :
76+ return [$ key , null ];
77+ default :
78+ return [$ key , $ val ];
79+ }
80+ }
81+ }
Original file line number Diff line number Diff line change @@ -38,3 +38,9 @@ function collection($data = [])
3838 return new \Simps \Utils \Collection ($ data );
3939 }
4040}
41+ if (! function_exists ('env ' )) {
42+ function env ($ key , $ default = null )
43+ {
44+ return container ()->get (\Simps \Utils \Env::class)->get ($ key , $ default );
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments