Passed
Push — master ( 4b3d26...06dcf5 )
by Enjoys
12:36 queued 13s
created

Variables::resolve()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 21
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 32
ccs 18
cts 18
cp 1
crap 5
rs 9.2728
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace Enjoys\Dotenv;
7
8
9
use Enjoys\Dotenv\Exception\InvalidArgumentException;
10
11
final class Variables
12
{
13 51
    public function __construct(private Dotenv $dotenv)
14
    {
15
    }
16
17 47
    public function resolve(string $key, ?string $value): ?string
18
    {
19 47
        if ($value === null) {
20 4
            return null;
21
        }
22 46
        $result = preg_replace_callback(
23
            '/(\${(?<variable>.+?)(?<default_value>:[-=?][^}]*)?})/',
24 46
            function (array $matches): string {
25 21
                $env = getenv($matches['variable']) ?: null;
26
27
                /** @var string|bool|int|float|null $val */
28 19
                $val =
29 21
                    $env ??
30 19
                    $this->dotenv->getEnvCollection()->get($matches['variable']) ??
31 13
                    $this->dotenv->getEnvRawArray()[$matches['variable']] ??
32 7
                    ($matches['default_value'] ? $this->resolveDefaultValue(
33 6
                        $matches['default_value'],
34 6
                        $matches['variable']
35 5
                    ) : null) ??
36
                    '';
37
38 19
                return Helper::scalarValueToString($val);
39
            },
40
            $value,
41
            flags: PREG_UNMATCHED_AS_NULL
42
        );
43
44 45
        if (preg_match('/(\${(.+?)})/', $result)) {
45 1
            return $this->resolve($key, $result);
46
        }
47
48 45
        return $result;
49
    }
50
51 6
    private function resolveDefaultValue(string $default_value, string $variable): string
52
    {
53 6
        $value = substr($default_value, 2);
54
55 6
        if ('?' === $default_value[1]) {
56 2
            throw new InvalidArgumentException(sprintf('Not set variable ${%s}. %s', $variable, $value));
57
        }
58
59 4
        if ('=' === $default_value[1]) {
60 3
            $this->dotenv->populate(
61
                $variable,
62
                $value,
63
            );
64
        }
65 4
        return $value;
66
    }
67
}
68