114 lines
2.7 KiB
PHP
114 lines
2.7 KiB
PHP
<?php
|
|
/**
|
|
* Bootstrap de configuration.
|
|
* Charge les secrets depuis les variables d'environnement ou un fichier local non versionne.
|
|
*/
|
|
|
|
if (!function_exists('loadLocalConfig')) {
|
|
/**
|
|
* Charge la configuration locale optionnelle.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
function loadLocalConfig(): array
|
|
{
|
|
static $config = null;
|
|
|
|
if ($config !== null) {
|
|
return $config;
|
|
}
|
|
|
|
$config = [];
|
|
$paths = [
|
|
__DIR__ . '/local.php',
|
|
dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config.local.php',
|
|
];
|
|
|
|
foreach ($paths as $path) {
|
|
if (!is_file($path)) {
|
|
continue;
|
|
}
|
|
|
|
$loaded = require $path;
|
|
if (is_array($loaded)) {
|
|
$config = array_replace($config, $loaded);
|
|
}
|
|
}
|
|
|
|
return $config;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('config_value')) {
|
|
/**
|
|
* Retourne une valeur de configuration issue de l'environnement ou du fichier local.
|
|
*/
|
|
function config_value(string $key, mixed $default = null): mixed
|
|
{
|
|
$envKey = strtoupper(str_replace('.', '_', $key));
|
|
|
|
$sources = [
|
|
getenv($envKey),
|
|
$_ENV[$envKey] ?? null,
|
|
$_SERVER[$envKey] ?? null,
|
|
];
|
|
|
|
foreach ($sources as $value) {
|
|
if ($value !== false && $value !== null && $value !== '') {
|
|
return $value;
|
|
}
|
|
}
|
|
|
|
$localConfig = loadLocalConfig();
|
|
return $localConfig[$key] ?? $default;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('config_required')) {
|
|
/**
|
|
* Retourne une valeur de configuration obligatoire.
|
|
*/
|
|
function config_required(string $key): string
|
|
{
|
|
$value = config_value($key);
|
|
|
|
if (!is_scalar($value) || trim((string) $value) === '') {
|
|
throw new RuntimeException("Configuration manquante: {$key}");
|
|
}
|
|
|
|
return trim((string) $value);
|
|
}
|
|
}
|
|
|
|
if (!function_exists('config_bool')) {
|
|
/**
|
|
* Retourne une valeur booleenne interpretee proprement.
|
|
*/
|
|
function config_bool(string $key, bool $default = false): bool
|
|
{
|
|
$value = config_value($key, $default);
|
|
|
|
if (is_bool($value)) {
|
|
return $value;
|
|
}
|
|
|
|
$filtered = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
|
return $filtered ?? $default;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('config_int')) {
|
|
/**
|
|
* Retourne une valeur entiere.
|
|
*/
|
|
function config_int(string $key, int $default = 0): int
|
|
{
|
|
$value = config_value($key, $default);
|
|
|
|
if (is_int($value)) {
|
|
return $value;
|
|
}
|
|
|
|
return is_numeric($value) ? (int) $value : $default;
|
|
}
|
|
}
|