Issues (9)

src/Config/ConfigManager.php (1 issue)

Severity
1
<?php
2
3
/**
4
 * This file is part of byrokrat\giroapp.
5
 *
6
 * byrokrat\giroapp is free software: you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * byrokrat\giroapp is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with byrokrat\giroapp. If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 * Copyright 2016-21 Hannes Forsgård
20
 */
21
22
declare(strict_types=1);
23
24
namespace byrokrat\giroapp\Config;
25
26
use byrokrat\giroapp\Exception\InvalidConfigException;
27
28
class ConfigManager
29
{
30
    /**
31
     * @var array<string, string>
32
     */
33
    private $configs = [];
34
35
    public function __construct(RepositoryInterface ...$repos)
36
    {
37
        foreach ($repos as $repo) {
38
            $this->loadRepository($repo);
39
        }
40
    }
41
42
    public function loadRepository(RepositoryInterface $configs): void
43
    {
44
        $this->configs = array_merge($this->configs, $configs->getConfigs());
45
    }
46
47
    public function getConfig(string $name): ConfigInterface
48
    {
49
        return new LazyConfig(function () use ($name) {
50
            if (!isset($this->configs[$name])) {
51
                throw new InvalidConfigException("Configuration for '$name' missing.");
52
            }
53
54
            $value = $this->configs[$name];
55
56
            if (!is_string($value)) {
0 ignored issues
show
The condition is_string($value) is always true.
Loading history...
57
                throw new InvalidConfigException("Configuration '$name' must be string, found: " . gettype($value));
58
            }
59
60
            $value = preg_replace_callback(
61
                '/%([^%]+)%/',
62
                function ($matches) {
63
                    return $this->getConfigValue($matches[1]);
64
                },
65
                $value
66
            );
67
68
            return $value;
69
        });
70
    }
71
72
    public function getConfigValue(string $name): string
73
    {
74
        return $this->getConfig($name)->getValue();
75
    }
76
}
77