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

Variables   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 30
c 1
b 0
f 0
dl 0
loc 55
ccs 26
cts 26
cp 1
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A resolve() 0 32 5
A resolveDefaultValue() 0 15 3
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