|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Micro\Framework\Kernel\Configuration; |
| 4 | + |
| 5 | +use Micro\Framework\Kernel\Configuration\Exception\InvalidConfigurationException; |
| 6 | + |
| 7 | +class DefaultApplicationConfiguration implements ApplicationConfigurationInterface |
| 8 | +{ |
| 9 | + private const BOOLEAN_TRUE = [ |
| 10 | + 'true', 'on', '1', 'yes' |
| 11 | + ]; |
| 12 | + |
| 13 | + /** |
| 14 | + * @param array<string, mixed> $configuration |
| 15 | + */ |
| 16 | + public function __construct(private readonly array $configuration) |
| 17 | + { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * {@inheritDoc} |
| 22 | + */ |
| 23 | + public function get(string $key, $default = null, bool $nullable = true): mixed |
| 24 | + { |
| 25 | + if(is_bool($default)) { |
| 26 | + return $this->getBooleanValue($key, $default); |
| 27 | + } |
| 28 | + |
| 29 | + $value = $this->getValue($key, $default); |
| 30 | + |
| 31 | + if($nullable === false && !$value && !is_numeric($value)) { |
| 32 | + throw new InvalidConfigurationException(sprintf('Configuration key "%s" can not be NULL', $key)); |
| 33 | + } |
| 34 | + |
| 35 | + return $value; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @param string $key |
| 40 | + * @param bool $default |
| 41 | + * |
| 42 | + * @return bool |
| 43 | + */ |
| 44 | + protected function getBooleanValue(string $key, bool $default): bool |
| 45 | + { |
| 46 | + $value = $this->getValue($key, $default); |
| 47 | + if($value === null) { |
| 48 | + return $default; |
| 49 | + } |
| 50 | + |
| 51 | + return in_array(mb_strtolower($value), self::BOOLEAN_TRUE, true); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @param string $key |
| 56 | + * @param mixed $default |
| 57 | + * |
| 58 | + * @return mixed |
| 59 | + */ |
| 60 | + protected function getValue(string $key, mixed $default): mixed |
| 61 | + { |
| 62 | + return $this->configuration[$key] ?? $default; |
| 63 | + } |
| 64 | +} |
0 commit comments