|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Micro framework package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Stanislau Komar <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Micro\Framework\Kernel\Configuration; |
|
13
|
|
|
|
|
14
|
|
|
use Micro\Framework\Kernel\Configuration\Exception\InvalidConfigurationException; |
|
15
|
|
|
|
|
16
|
|
|
class DefaultApplicationConfiguration implements ApplicationConfigurationInterface |
|
17
|
|
|
{ |
|
18
|
|
|
private const BOOLEAN_TRUE = [ |
|
19
|
|
|
'true', 'on', '1', 'yes', |
|
20
|
|
|
]; |
|
21
|
|
|
|
|
22
|
|
|
private const BOOLEAN_FALSE = [ |
|
23
|
|
|
'false', 'off', '0', 'no', |
|
24
|
|
|
]; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param array<string, mixed> $configuration |
|
28
|
|
|
*/ |
|
29
|
8 |
|
public function __construct(private readonly array $configuration) |
|
30
|
|
|
{ |
|
31
|
8 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritDoc} |
|
35
|
|
|
*/ |
|
36
|
9 |
|
public function get(string $key, mixed $default = null, bool $nullable = true): mixed |
|
37
|
|
|
{ |
|
38
|
9 |
|
if (\is_bool($default)) { |
|
39
|
|
|
try { |
|
40
|
4 |
|
return $this->getBooleanValue($key, $default); |
|
41
|
1 |
|
} catch (\InvalidArgumentException $exception) { |
|
42
|
1 |
|
throw new InvalidConfigurationException(sprintf('Configuration key "%s" can not be converted to boolean', $key), 0, $exception); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
5 |
|
$value = $this->getValue($key, $default); |
|
47
|
|
|
|
|
48
|
5 |
|
if (false === $nullable && !$value && !is_numeric($value)) { |
|
49
|
2 |
|
throw new InvalidConfigurationException(sprintf('Configuration key "%s" can not be NULL', $key)); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
3 |
|
return $value; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
4 |
|
protected function getBooleanValue(string $key, bool $default): bool |
|
56
|
|
|
{ |
|
57
|
4 |
|
$value = $this->getValue($key, $default); |
|
58
|
4 |
|
if (\is_bool($value)) { |
|
59
|
3 |
|
return $value; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
3 |
|
if (null === $value) { |
|
63
|
|
|
return $default; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
3 |
|
$value = mb_strtolower($value); |
|
67
|
|
|
|
|
68
|
3 |
|
if (\in_array($value, self::BOOLEAN_TRUE, true)) { |
|
69
|
1 |
|
return true; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
2 |
|
if (\in_array($value, self::BOOLEAN_FALSE, true)) { |
|
73
|
1 |
|
return false; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
throw new \InvalidArgumentException('Value can not be converted to boolean.'); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
9 |
|
protected function getValue(string $key, mixed $default): mixed |
|
80
|
|
|
{ |
|
81
|
9 |
|
return $this->configuration[$key] ?? $default; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|