Files
saasshop/app/Providers/AppServiceProvider.php

73 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Providers;
use App\Models\SystemConfig;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// 从数据库 system_configs 自动注入可配置项到 config(),用于“总台可治理/可配置”的运营闭环。
//
// 安全阀:
// - 在测试/首次安装阶段,可能尚未执行迁移;此时 system_configs 表不存在,必须跳过。
// - 任意配置项解析失败(如 JSON 格式错误)也不应阻断应用启动。
if (! Schema::hasTable('system_configs')) {
return;
}
try {
$configs = SystemConfig::query()
->where('autoload', true)
->orderBy('id')
->get(['config_key', 'config_value', 'value_type']);
foreach ($configs as $row) {
$key = (string) ($row->config_key ?? '');
if ($key === '') {
continue;
}
$type = (string) ($row->value_type ?? 'string');
$raw = $row->config_value;
$value = match ($type) {
'boolean' => in_array(strtolower((string) $raw), ['1', 'true', 'yes', 'on'], true),
'number' => is_numeric($raw) ? (float) $raw : 0.0,
'json' => (function () use ($raw) {
$decoded = json_decode((string) ($raw ?? ''), true);
return json_last_error() === JSON_ERROR_NONE ? $decoded : null;
})(),
default => $raw,
};
// JSON 解析失败时直接跳过(不影响系统启动)
if ($type === 'json' && $value === null) {
continue;
}
// 注意:使用 dot key 注入到 config()例如saasshop.amounts.tolerance
config([$key => $value]);
}
} catch (\Throwable $e) {
// 不阻断启动:治理配置加载失败时,回退到 config/*.php 默认值
return;
}
}
}