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