Completed
Push — master ( 86d06a...811f1b )
by TJ
02:37
created

DotenvEditor   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 2
dl 0
loc 82
ccs 35
cts 35
cp 1
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 10 2
A set() 0 6 1
A getEnv() 0 6 2
A save() 0 6 1
A addEmptyLine() 0 6 1
A heading() 0 10 2
A has() 0 4 1
A __destruct() 0 6 2
A format() 0 10 3
1
<?php
2
3
namespace sixlive\DotenvEditor;
4
5
use sixlive\DotenvEditor\Support\Arr;
6
7
class DotenvEditor
8
{
9
    protected $env = [];
10
11
    /**
12
     * @var \sixlive\DotenvEditor\EnvFile
13
     */
14
    protected $envFile;
15
16 8
    public function load($path)
17
    {
18 8
        $this->envFile = new EnvFile($path);
19
20 8
        if ($this->envFile->isEmpty()) {
21 3
            $this->env = array_merge($this->env, $this->envFile->toArray());
22
        }
23
24 8
        return $this;
25
    }
26
27 8
    public function set($key, $value)
28
    {
29 8
        $this->env[$key] = $value;
30
31 8
        return $this;
32
    }
33
34 3
    public function getEnv($key = '')
35
    {
36 3
        return isset($this->env[$key])
37 1
            ? $this->env[$key]
38 3
            : $this->env;
39
    }
40
41 6
    public function save()
42
    {
43 6
        $this->envFile->write($this->format());
44
45 6
        return $this;
46
    }
47
48 2
    public function addEmptyLine()
49
    {
50 2
        $this->env[] = '';
51
52 2
        return $this;
53
    }
54
55 3
    public function heading($heading)
56
    {
57 3
        if (! empty(end($this->env))) {
58 1
            $this->addEmptyLine();
59
        }
60
61 3
        $this->env[] = sprintf('# %s', $heading);
62
63 3
        return $this;
64
    }
65
66 1
    public function has($key)
67
    {
68 1
        return isset($this->env[$key]);
69
    }
70
71 10
    public function __destruct()
72
    {
73 10
        if ($this->envFile) {
74 8
            $this->envFile->close();
75
        }
76 10
    }
77
78
    private function format()
79
    {
80 6
        $valuePairs = Arr::mapWithKeys($this->env, function ($item, $key) {
81 6
            return ! empty($item) && ! is_int($key)
82 6
                ? sprintf('%s=%s', $key, $item)
83 6
                : $item;
84 6
        });
85
86 6
        return implode("\n", $valuePairs);
87
    }
88
}
89