Completed
Push — b0.24.0 ( 127adf...72b353 )
by Sebastian
13:53 queued 06:30
created

DotEnv::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 0
cts 6
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 6
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
     * Get a value from environment.
23
     *
24
     * @param string $key
25
     * @param mixed  $default
26
     */
27
    public function get(string $key, $default = null)
28
    {
29
        if (($value = getenv($key)) === false) {
30
            return $default;
31
        }
32
33
        return $value;
34
    }
35
36
    /**
37
     * Load environment variables from file.
38
     *
39
     * @param string $file Path to .env file
40
     */
41
    public function load(string $file): bool
42
    {
43
        if (!is_file($file)) {
44
            return false;
45
        }
46
47
        $content = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
48
49
        foreach ($content as $line) {
50
            $line = rtrim(ltrim($line));
51
52
            //check if the line contains a key value pair
53
            if (!preg_match("/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/", $line)) {
54
                continue;
55
            }
56
57
            [$key, $value] = explode('=', $line);
58
59
            //set to empty value
60
            if (strlen($value) === 0) {
61
                putenv("{$key}=");
62
                continue;
63
            }
64
65
            $edges = $value[0].$value[-1];
66
67
            if ($edges === "''" || $edges === '""') {
68
                $value = substr($value, 1, -1);
69
            }
70
71
            putenv("{$key}={$value}");
72
        }
73
74
        return true;
75
    }
76
}
77