JsonRuntimeConfig.php
Pfad: src/Infrastructure/Rechnung/JsonRuntimeConfig.php
Ext: php
Größe: 1921 Bytes
Geändert: 2026-07-16 17:38:52+02
<?php
declare(strict_types=1);
namespace Demo\Infrastructure\Rechnung;
use JsonException;
use RuntimeException;
final class JsonRuntimeConfig
{
/**
* @param array<string,mixed> $defaults
* @return array<string,mixed>
*/
public static function load(string $file, string $label, array $defaults = []): array
{
if (!is_file($file)) {
return $defaults;
}
$raw = file_get_contents($file);
if (!is_string($raw)) {
throw new RuntimeException($label . ' kann nicht gelesen werden');
}
try {
$decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
throw new RuntimeException($label . ' ist kein valides JSON', 0, $error);
}
if (!is_array($decoded)) {
throw new RuntimeException($label . ' ist kein JSON-Objekt');
}
return array_replace($defaults, $decoded);
}
/**
* @param array<string,mixed> $source
* @param list<string> $aliases
*/
public static function string(array $source, string $key, array $aliases = [], string $default = ''): string
{
foreach ([$key, ...$aliases] as $candidate) {
$value = $source[$candidate] ?? null;
if ((is_string($value) || is_int($value) || is_float($value)) && trim((string) $value) !== '') {
return (string) $value;
}
}
return $default;
}
public static function bool(mixed $value): bool
{
if (is_bool($value)) { return $value; }
if (is_int($value)) { return $value > 0; }
return is_string($value) && filter_var($value, FILTER_VALIDATE_BOOL) !== false;
}
public static function environment(string $name): ?string
{
$value = getenv($name);
return $value === false || $value === '' ? null : $value;
}
}