Repository navigation
Expand file tree
/
Copy pathDotenv.php
More file actions
67 lines (57 loc) · 1.87 KB
/
Copy pathDotenv.php
File metadata and controls
67 lines (57 loc) · 1.87 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
56
57
58
59
60
61
62
63
64
65
66
<?php
/**
* Dotenv
*
* Loads a `.env` file in the given directory and sets the environment vars
*/
class Dotenv
{
/**
* Load `.env` file in given directory
*/
public static function load($path, $file = '.env')
{
if(!is_string($file)) {
$file = '.env';
}
$filePath = rtrim($path, '/') . '/' . $file;
if(!file_exists($filePath)) {
throw new \InvalidArgumentException("Dotenv: Environment file .env not found. Create file with your environment settings at " . $filePath);
}
// Read file and get all lines
$fc = file_get_contents($filePath);
$lines = preg_split('/\r\n|\r|\n/', $fc);
foreach($lines as $line) {
// Only use non-empty lines that look like setters
if(!empty($line) && strpos($line, '=') !== false) {
// Strip quotes because putenv can't handle them. Also remove 'export' if present
$line = trim(str_replace(array('export ', '\'', '"'), '', $line));
putenv($line);
// Set PHP superglobals
list($key, $val) = explode('=', $line, 2);
$_ENV[$key] = $val;
$_SERVER[$key] = $val;
}
}
}
/**
* Require specified ENV vars to be present, or throw Exception
*
* @throws \RuntimeException
*/
public static function required($env)
{
$envs = (array) $env;
$missingEnvs = array();
foreach($envs as $env) {
// Check $_SERVER in addition to ENV
if(!isset($_SERVER[$env]) || getenv($env) === false) {
$missingEnvs[] = $env;
}
}
if(!empty($missingEnvs)) {
throw new \RuntimeException("Required ENV vars missing: '" . implode("', '", $missingEnvs) . "'");
}
return true;
}
}