Completed
Push — master ( 2923a6...86d06a )
by TJ
02:57
created

DotenvEditor::__destruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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
    private function format()
72
    {
73 6
        $valuePairs = Arr::mapWithKeys($this->env, function ($item, $key) {
74 6
            return ! empty($item) && ! is_int($key)
75 6
                ? sprintf('%s=%s', $key, $item)
76 6
                : $item;
77 6
        });
78
79 6
        return implode("\n", $valuePairs);
80
    }
81
}
82