Env::get()   C
last analyzed

Complexity

Conditions 14
Paths 12

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 31
rs 6.2666
cc 14
nc 12
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
The constant Luolongfei\Lib\ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
29
    }
30
31
    public static function instance($fileName = '.env')
32
    {
33
        if (!self::$instance instanceof self) {
0 ignored issues
show
introduced by
self::instance is always a sub-type of self.
Loading history...
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
}