1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Linna Framework. |
5
|
|
|
* |
6
|
|
|
* @author Sebastian Rapetti <[email protected]> |
7
|
|
|
* @copyright (c) 2018, Sebastian Rapetti |
8
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types = 1); |
11
|
|
|
|
12
|
|
|
namespace Linna\DotEnv; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* DotEnv. |
16
|
|
|
* |
17
|
|
|
* Load variables from a .env file to environment. |
18
|
|
|
*/ |
19
|
|
|
class DotEnv |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array Matches for particula values |
23
|
|
|
*/ |
24
|
|
|
private static $valuesMatches = [ |
25
|
|
|
'true' => true, |
26
|
|
|
'(true)' => true, |
27
|
|
|
'false' => false, |
28
|
|
|
'(false)' => false, |
29
|
|
|
'empty' => '', |
30
|
|
|
'(empty)' => '', |
31
|
|
|
'null' => null, |
32
|
|
|
'(null)' => null, |
33
|
|
|
]; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Get a value from environment. |
37
|
|
|
* |
38
|
|
|
* @param string $key Key name |
39
|
|
|
* @param mixed $default Default value if key not found |
40
|
|
|
*/ |
41
|
31 |
|
public function get(string $key, $default = null) |
42
|
|
|
{ |
43
|
31 |
|
if (($value = getenv($key)) === false) { |
44
|
1 |
|
return $default; |
45
|
|
|
} |
46
|
|
|
|
47
|
30 |
|
return $value; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Load environment variables from file. |
52
|
|
|
* |
53
|
|
|
* @param string $file Path to .env file |
54
|
|
|
* |
55
|
|
|
* @return bool |
56
|
|
|
*/ |
57
|
32 |
|
public function load(string $file): bool |
58
|
|
|
{ |
59
|
32 |
|
if (!file_exists($file)) { |
60
|
1 |
|
return false; |
61
|
|
|
} |
62
|
|
|
|
63
|
31 |
|
$content = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
64
|
|
|
|
65
|
31 |
|
foreach ($content as $line) { |
66
|
31 |
|
$line = rtrim(ltrim($line)); |
67
|
|
|
|
68
|
|
|
//check if the line contains a key value pair |
69
|
31 |
|
if (!preg_match("/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/", $line)) { |
70
|
16 |
|
continue; |
71
|
|
|
} |
72
|
|
|
|
73
|
31 |
|
[$key, $value] = explode('=', $line); |
74
|
|
|
|
75
|
|
|
//matches for particula values |
76
|
31 |
|
if (array_key_exists(strtolower($value), self::$valuesMatches)) { |
77
|
15 |
|
$value = self::$valuesMatches[strtolower($value)]; |
78
|
15 |
|
putenv("{$key}={$value}"); |
79
|
15 |
|
continue; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
//set to empty value |
83
|
31 |
|
if (strlen($value) === 0) { |
84
|
16 |
|
putenv("{$key}="); |
85
|
16 |
|
continue; |
86
|
|
|
} |
87
|
|
|
|
88
|
31 |
|
$edges = $value[0].$value[-1]; |
89
|
|
|
|
90
|
31 |
|
if ($edges === "''" || $edges === '""') { |
91
|
31 |
|
$value = substr($value, 1, -1); |
92
|
|
|
} |
93
|
|
|
|
94
|
31 |
|
putenv("{$key}={$value}"); |
95
|
|
|
} |
96
|
|
|
|
97
|
31 |
|
return true; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|