Passed
Push — master ( 54d817...889309 )
by Enjoys
02:29
created

Variables::scalarValueToString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

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