mirror of
https://devops.lemonos.cn/lawson/FendxPHP.git
synced 2026-06-15 23:12:49 +08:00
86 lines
1.9 KiB
PHP
86 lines
1.9 KiB
PHP
|
|
<?php
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace Fendx\Core\Config;
|
||
|
|
|
||
|
|
use Fendx\Common\Exception\BusinessException;
|
||
|
|
|
||
|
|
final class Config
|
||
|
|
{
|
||
|
|
private static array $data = [];
|
||
|
|
private static array $cache = [];
|
||
|
|
|
||
|
|
public static function load(array $config): void
|
||
|
|
{
|
||
|
|
self::$data = $config;
|
||
|
|
self::$cache = [];
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function get(string $key, mixed $default = null): mixed
|
||
|
|
{
|
||
|
|
if ($key === '') {
|
||
|
|
return $default;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 使用缓存提高性能
|
||
|
|
if (isset(self::$cache[$key])) {
|
||
|
|
return self::$cache[$key];
|
||
|
|
}
|
||
|
|
|
||
|
|
$parts = explode('.', $key);
|
||
|
|
$cur = self::$data;
|
||
|
|
|
||
|
|
foreach ($parts as $part) {
|
||
|
|
if (!is_array($cur) || !array_key_exists($part, $cur)) {
|
||
|
|
self::$cache[$key] = $default;
|
||
|
|
return $default;
|
||
|
|
}
|
||
|
|
$cur = $cur[$part];
|
||
|
|
}
|
||
|
|
|
||
|
|
self::$cache[$key] = $cur;
|
||
|
|
return $cur;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function set(string $key, mixed $value): void
|
||
|
|
{
|
||
|
|
$parts = explode('.', $key);
|
||
|
|
$cur = &self::$data;
|
||
|
|
|
||
|
|
foreach ($parts as $part) {
|
||
|
|
if (!is_array($cur)) {
|
||
|
|
$cur = [];
|
||
|
|
}
|
||
|
|
if (!array_key_exists($part, $cur)) {
|
||
|
|
$cur[$part] = [];
|
||
|
|
}
|
||
|
|
$cur = &$cur[$part];
|
||
|
|
}
|
||
|
|
|
||
|
|
$cur = $value;
|
||
|
|
|
||
|
|
// 清除相关缓存
|
||
|
|
foreach (array_keys(self::$cache) as $cacheKey) {
|
||
|
|
if (str_starts_with($cacheKey, $key)) {
|
||
|
|
unset(self::$cache[$cacheKey]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function has(string $key): bool
|
||
|
|
{
|
||
|
|
return self::get($key) !== null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function all(): array
|
||
|
|
{
|
||
|
|
return self::$data;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function clear(): void
|
||
|
|
{
|
||
|
|
self::$data = [];
|
||
|
|
self::$cache = [];
|
||
|
|
}
|
||
|
|
}
|