diff --git a/src/ZM/Config/RefactoredConfig.php b/src/ZM/Config/RefactoredConfig.php index 71e279a5..8974b7ec 100644 --- a/src/ZM/Config/RefactoredConfig.php +++ b/src/ZM/Config/RefactoredConfig.php @@ -22,22 +22,22 @@ class RefactoredConfig /** * @var array 已加载的配置文件 */ - private $loaded_files = []; + private array $loaded_files = []; /** * @var array 配置文件路径 */ - private $config_paths; + private array $config_paths; /** * @var string 当前环境 */ - private $environment; + private string $environment; /** * @var Config 内部配置容器 */ - private $holder; + private Config $holder; /** * 构造配置实例 @@ -256,7 +256,7 @@ class RefactoredConfig // 判断文件格式是否支持 [$group, $ext, $load_type, $env] = $this->getFileMeta($path); if (!in_array($ext, self::ALLOWED_FILE_EXTENSIONS, true)) { - throw new ConfigException('E00079', "不支持的配置文件格式:{$ext}"); + throw ConfigException::unsupportedFileType($path); } // 读取并解析配置 @@ -267,7 +267,11 @@ class RefactoredConfig $config = require $path; break; case 'json': - $config = json_decode($content, true); + try { + $config = json_decode($content, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw ConfigException::loadConfigFailed($path, $e->getMessage()); + } break; case 'yaml': case 'yml': @@ -277,7 +281,7 @@ class RefactoredConfig // TODO: 实现toml解析 break; default: - throw new ConfigException('E00079', "不支持的配置文件格式:{$ext}"); + throw ConfigException::unsupportedFileType($path); } // 加入配置 diff --git a/src/ZM/Exception/ConfigException.php b/src/ZM/Exception/ConfigException.php index d61d8f5e..369f2d93 100644 --- a/src/ZM/Exception/ConfigException.php +++ b/src/ZM/Exception/ConfigException.php @@ -8,8 +8,22 @@ use Throwable; class ConfigException extends ZMException { + public const UNSUPPORTED_FILE_TYPE = 'E00079'; + + public const LOAD_CONFIG_FAILED = 'E00080'; + public function __construct($err_code, $message = '', $code = 0, Throwable $previous = null) { parent::__construct(zm_internal_errcode($err_code) . $message, $code, $previous); } + + public static function unsupportedFileType(string $file_path): ConfigException + { + return new self(self::UNSUPPORTED_FILE_TYPE, "不支持的配置文件类型:{$file_path}"); + } + + public static function loadConfigFailed(string $file_path, string $message): ConfigException + { + return new self(self::LOAD_CONFIG_FAILED, "加载配置文件失败:{$file_path},{$message}"); + } } diff --git a/tests/ZM/Config/RefactoredConfigTest.php b/tests/ZM/Config/RefactoredConfigTest.php index 053550a8..37c00ed4 100644 --- a/tests/ZM/Config/RefactoredConfigTest.php +++ b/tests/ZM/Config/RefactoredConfigTest.php @@ -13,7 +13,7 @@ use ZM\Utils\ReflectionUtil; */ class RefactoredConfigTest extends TestCase { - private static $config; + private static RefactoredConfig $config; public static function setUpBeforeClass(): void {