Completed
Push — master ( a36c65...1e9f43 )
by Martin
03:21
created

EnvAccessor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 52
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B get() 0 14 5
A load() 0 19 4
1
<?php
2
3
4
namespace wodCZ\NetteDotenv;
5
6
use Dotenv\Dotenv;
7
use Dotenv\Exception\InvalidPathException;
8
9
class EnvAccessor
10
{
11
    private $directory;
12
    private $fileName;
13
    private $overload;
14
    private $loaded;
15
    /** @var bool */
16
    private $localOnly;
17
18
    public function __construct($directory, $fileName = '.env', $overload = false, $localOnly = false)
19
    {
20
        $this->directory = $directory;
21
        $this->fileName = $fileName;
22
        $this->overload = $overload;
23
        $this->localOnly = $localOnly;
24
    }
25
26
    public function get($key, $default = null)
27
    {
28
        $this->load();
29
30
        if (PHP_MAJOR_VERSION === 5) {
31
            if ($this->localOnly) {
32
                trigger_error('localOnly option is only available in PHP 7');
33
            }
34
            $value = getenv($key);
35
            return $value === false ? $default : $value;
36
        }
37
        $value = getenv($key, $this->localOnly);
38
        return $value === false ? $default : $value;
39
    }
40
41
    private function load()
42
    {
43
        if ($this->loaded) {
44
            return;
45
        }
46
        try {
47
            // Load variables from .env file
48
            $loader = new Dotenv($this->directory, $this->fileName);
49
50
            if ($this->overload) {
51
                $loader->overload();
52
            } else {
53
                $loader->load();
54
            }
55
        } catch (InvalidPathException $e) {
56
            // If .env file doesn't exist, silently continue
57
        }
58
        $this->loaded = true;
59
    }
60
}
61