Loader::putenv()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Rfussien\Dotenv;
4
5
class Loader
6
{
7
    /**
8
     * Set the env file
9
     */
10
    protected $file;
11
12
    protected $parser;
13
14 21
    public function __construct($path, $filename = '.env')
15
    {
16 21
        $path = rtrim($path, DIRECTORY_SEPARATOR);
17
18 21
        $this->file = $path . DIRECTORY_SEPARATOR . $filename;
19 21
    }
20
21
    /**
22
     * parse and set the env
23
     *
24
     * @return self
25
     */
26 18
    public function load()
27
    {
28 18
        $this->parse();
29
30 18
        $this->toEnv();
31
32 18
        return $this;
33
    }
34
35
    /**
36
     * Parse the env file
37
     *
38
     * @return self
39
     */
40 18
    public function parse()
41
    {
42 18
        $this->parser = new Parser;
43
44 18
        $this->parser->parse($this->file);
45
46 18
        return $this;
47
    }
48
49
    /**
50
     * Return the parser
51
     *
52
     * @return Rfussien\Dotenv\Parser
53
     */
54 3
    public function getParser()
55
    {
56 3
        return $this->parser;
57
    }
58
59 21
    public function toEnv()
60
    {
61 21
        if (!isset($this->parser)) {
62 3
            throw new \LogicException("You must call parse() before", 1);
63
        }
64
65 18
        foreach ($this->parser->getContent() as $key => $value) {
66 18
            static::putenv($key, $value);
67 12
        }
68
69 18
        return $this;
70
    }
71
72
    /**
73
     * Set an env variable into $_ENV, $_SERVER and putenv
74
     */
75 18
    public static function putenv($key, $value)
76
    {
77 18
        $_ENV[$key]    = $value;
78 18
        $_SERVER[$key] = $value;
79
80
        /*
81
         * putenv only accept string value
82
         */
83 18
        $value = $value === null ? 'null' : $value;
84 18
        putenv("$key=$value");
85 18
    }
86
87
    /**
88
     * Return the value of an environment variable
89
     */
90 12
    public static function getenv($key, $default = null)
91
    {
92 8
        switch (true) {
93 12
            case array_key_exists($key, $_ENV):
94 3
                return $_ENV[$key];
95
96 9
            case array_key_exists($key, $_SERVER):
97 3
                return $_SERVER[$key];
98
99 4
            default:
100 6
                $value = getenv($key);
101 6
                return $value === false ? $default : $value;
102 4
        }
103
    }
104
}
105