Completed
Pull Request — master (#4415)
by Craig
05:57
created

LocalDotEnvHelper::writeLocalEnvVars()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 2
nop 2
dl 0
loc 21
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\Bundle\CoreBundle\Helper;
15
16
use Symfony\Component\Filesystem\Filesystem;
17
18
class LocalDotEnvHelper
19
{
20
    /**
21
     * @var string
22
     */
23
    private $projectDir;
24
25
    public function __construct(
26
        string $projectDir
27
    ) {
28
        $this->projectDir = $projectDir;
29
    }
30
31
    /**
32
     * Add $newVars to the .env.local file. If true === $override, remove existing values.
33
     * Prepend value with '!' to disable pseudo-urlencoding that value
34
     */
35
    public function writeLocalEnvVars(array $newVars, bool $override = false): void
36
    {
37
        $localEnvPath = $this->projectDir . '/.env.local';
38
        $fileSystem = new Filesystem();
39
        $vars = [];
40
        if (!$override && $fileSystem->exists($localEnvPath)) {
41
            $content = explode("\n", file_get_contents($localEnvPath));
42
            foreach ($content as $line) {
43
                if (empty($line) || '#' === $line[0]) {
44
                    continue;
45
                }
46
                [$key, $value] = explode('=', $line, 2);
47
                if (isset($newVars[$key])) {
48
                    unset($vars[$key]); // removing the old $key preserves the order of the $newVars when set
49
                } else {
50
                    $vars[$key] = '!' . $value; // never encode existing values
51
                }
52
            }
53
        }
54
        $vars = $vars + array_diff_assoc($newVars, $vars);
55
        $fileSystem->dumpFile($localEnvPath, $this->varsToString($vars));
56
    }
57
58
    private function varsToString(array $vars): string
59
    {
60
        $lines = [];
61
        foreach ($vars as $key => $value) {
62
            if ('!' === mb_substr((string) $value, 0, 1)) {
63
                $value = mb_substr((string) $value, 1);
64
            } else {
65
                $quote = in_array(mb_substr((string) $value, 0, 1), ['\'', '"']) ? '\'' : '';
66
                $value = !empty($quote) ? trim((string) $value, '\'"') : (string) $value;
67
                $value =  $quote . urlencode($value) . $quote;
68
            }
69
            $lines[] = $key . '=' . $value;
70
        }
71
72
        return trim(implode("\n", $lines));
73
    }
74
}
75