Passed
Push — b0.24.0 ( 72b353...b56eac )
by Sebastian
04:05
created

DotEnv::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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