Passed
Push — master ( a72ed3...35232d )
by Melech
04:02
created

Config::fromEnv()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
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 Valkyrja\Support;
15
16
use function constant;
17
use function defined;
18
use function is_callable;
19
20
/**
21
 * Abstract Class Config.
22
 *
23
 * @author Melech Mizrachi
24
 */
25
abstract class Config
26
{
27
    /**
28
     * The model properties env keys.
29
     *
30
     * @var array<string, string>
31
     */
32
    protected static array $envNames = [];
33
34
    /**
35
     * Create config from Env.
36
     *
37
     * @param class-string $env The env
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
38
     */
39
    public static function fromEnv(string $env): static
40
    {
41
        $new = new static();
42
43
        $new->setPropertiesFromEnv($env);
44
45
        return $new;
46
    }
47
48
    /**
49
     * Set properties from env.
50
     *
51
     * @param class-string $env The env
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
52
     */
53
    public function setPropertiesFromEnv(string $env): void
54
    {
55
        foreach (static::$envNames as $propertyName => $envName) {
56
            if (defined("$env::$envName")) {
57
                $constantValue = constant("$env::$envName");
58
59
                if (is_callable($constantValue)) {
60
                    $this->$propertyName = $constantValue()
61
                        ?? $this->$propertyName;
62
63
                    continue;
64
                }
65
66
                $this->$propertyName = $constantValue
67
                    ?? $this->$propertyName;
68
            }
69
        }
70
    }
71
}
72