84 lines
2.9 KiB
PHP
84 lines
2.9 KiB
PHP
<?php
|
||
|
||
namespace App\Providers;
|
||
|
||
use App\Models\SystemConfig;
|
||
use Illuminate\Pagination\Paginator;
|
||
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
|
||
{
|
||
// Admin: unify pagination view for back-office pages.
|
||
// 说明:不改变业务逻辑,仅统一分页 HTML 结构与样式基线(Ant Design Pro-ish)。
|
||
Paginator::defaultView('pagination.admin');
|
||
|
||
// 从数据库 system_configs 自动注入可配置项到 config(),用于“总台可治理/可配置”的运营闭环。
|
||
//
|
||
// 安全阀:
|
||
// - 在测试/首次安装阶段,可能尚未执行迁移;此时 system_configs 表不存在,必须跳过。
|
||
// - 任意配置项解析失败(如 JSON 格式错误)也不应阻断应用启动。
|
||
// 若数据库连接不可用(例如本地 mysql 未启动 / CI 环境),Schema::hasTable() 会直接抛异常。
|
||
// 这里加一层 try/catch,确保“治理配置加载”不会阻断应用启动。
|
||
try {
|
||
if (! Schema::hasTable('system_configs')) {
|
||
return;
|
||
}
|
||
} catch (\Throwable $e) {
|
||
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;
|
||
}
|
||
}
|
||
}
|