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

DotenvEditor::__destruct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
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