-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseEnv.php
More file actions
55 lines (47 loc) · 1.59 KB
/
Copy pathparseEnv.php
File metadata and controls
55 lines (47 loc) · 1.59 KB
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
<?php
function parseEnv($file)
{
if (!file_exists($file)) {
throw new Exception("The .env file does not exist.");
}
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$env = [];
foreach ($lines as $line) {
# Ignore comments
if (strpos(trim($line), '#') === 0) {
continue;
}
# Skip if line is malformed
if (!strpos($line, '=')) {
continue;
}
# Separate the key and value
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
# Handle quoted values
if (preg_match('/^"(.*)"$/', $value, $matches)) {
$value = str_replace('\n', "\n", $matches[1]);
} elseif (preg_match("/^'(.*)'$/", $value, $matches)) {
$value = $matches[1];
}
# Handle boolean and null values
if (strtolower($value) === 'true') {
$value = true;
} elseif (strtolower($value) === 'false') {
$value = false;
} elseif (strtolower($value) === 'null') {
$value = null;
}
# Handling nested variables (only if value is not null)
if ($value !== null) {
$value = preg_replace_callback('/\$\{(\w+)\}/', function ($matches) use ($env) {
return isset($env[$matches[1]]) ? $env[$matches[1]] : $matches[0];
}, $value);
}
# Storing in the environment and in the array for nested variables
putenv("$key=$value");
$_ENV[$key] = $value;
$env[$key] = $value;
}
}