Completed
Push — master ( 73295c...349be7 )
by David
02:23
created

EnvFile::set()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 27
rs 9.6333
c 0
b 0
f 0
cc 4
nc 6
nop 3
1
<?php
2
3
4
namespace TheAentMachine\AentDockerCompose\DockerCompose;
5
6
class EnvFile
7
{
8
    /**
9
     * @var string
10
     */
11
    private $filePath;
12
13
    public function __construct(string $filePath)
14
    {
15
16
        $this->filePath = $filePath;
17
    }
18
19
    /**
20
     * Adds or updates an environment variable.
21
     */
22
    public function set(string $key, string $value, string $comment = null): void
23
    {
24
        $content = $this->getContent();
25
        if ($this->has($key)) {
26
            // Note: if the key is already in the file, comments are not modified.
27
            $content = \preg_replace("/^$key=.*/m", $key.'='.$value, $content);
28
        } else {
29
            $commentLines = \explode("\n", $comment ?? '');
30
            $commentLines = \array_map(function (string $line) {
31
                return '# '.$line;
32
            }, $commentLines);
33
            $comments = \implode("\n", $commentLines);
34
            if ($comment) {
35
                $content .= <<<ENVVAR
36
$comments
37
38
ENVVAR;
39
            }
40
            $content .= <<<ENVVAR
41
$key=$value
42
43
ENVVAR;
44
        }
45
46
        $return = \file_put_contents($this->filePath, $content);
47
        if ($return === false) {
48
            throw new \RuntimeException('Unable to write file '.$this->filePath);
49
        }
50
    }
51
52
    private function has(string $envName): bool
53
    {
54
        if (!\file_exists($this->filePath)) {
55
            return false;
56
        }
57
        $content = $this->getContent();
58
        return (bool) \preg_match("/^$envName=/m", $content);
59
    }
60
61
    private function getContent(): string
62
    {
63
        $content = \file_get_contents($this->filePath);
64
        if ($content === false) {
65
            throw new \RuntimeException('Unable to read file '.$this->filePath);
66
        }
67
        return $content;
68
    }
69
}
70