From eb7e700e7c4a79b975912e7e9ef34254c6a04ee9 Mon Sep 17 00:00:00 2001 From: sunxyw Date: Tue, 23 Aug 2022 18:02:00 +0800 Subject: [PATCH] replace legacy config --- src/Globals/global_functions.php | 8 +-- src/ZM/Annotation/AnnotationParser.php | 3 +- src/ZM/Command/CheckConfigCommand.php | 3 +- .../Generate/SystemdGenerateCommand.php | 3 +- src/ZM/Config/ZMConfig.php | 49 ++++++++++++++++- .../Container/ContainerServicesProvider.php | 4 +- src/ZM/Event/Listener/MasterEventListener.php | 3 +- src/ZM/Event/Listener/WorkerEventListener.php | 3 +- src/ZM/Framework.php | 53 +++++++++---------- src/ZM/InstantApplication.php | 3 +- src/ZM/Store/MySQL/MySQLDriver.php | 3 +- src/ZM/Utils/HttpUtil.php | 15 +++--- 12 files changed, 94 insertions(+), 56 deletions(-) diff --git a/src/Globals/global_functions.php b/src/Globals/global_functions.php index 982ddf7b..3f4df067 100644 --- a/src/Globals/global_functions.php +++ b/src/Globals/global_functions.php @@ -143,7 +143,7 @@ function container(): ContainerInterface * 解析类实例(使用容器) * * @template T - * @param class-string $abstract + * @param class-string $abstract * @return Closure|mixed|T * @noinspection PhpDocMissingThrowsInspection */ @@ -157,7 +157,7 @@ function resolve(string $abstract, array $parameters = []) * 获取容器实例 * * @template T - * @param null|class-string $abstract + * @param null|class-string $abstract * @return Closure|ContainerInterface|mixed|T */ function app(string $abstract = null, array $parameters = []) @@ -196,8 +196,8 @@ function mysql_builder(string $name = '') * 传入数组,设置配置项 * 不传参数,返回配置容器 * - * @param null|string|array $key 键名 - * @param mixed $default 默认值 + * @param null|array|string $key 键名 + * @param mixed $default 默认值 * @return mixed|ZMConfig */ function config($key = null, $default = null) diff --git a/src/ZM/Annotation/AnnotationParser.php b/src/ZM/Annotation/AnnotationParser.php index 70f6f285..c897baf5 100644 --- a/src/ZM/Annotation/AnnotationParser.php +++ b/src/ZM/Annotation/AnnotationParser.php @@ -15,7 +15,6 @@ use ZM\Annotation\Http\Route; use ZM\Annotation\Interfaces\ErgodicAnnotation; use ZM\Annotation\Interfaces\Level; use ZM\Annotation\Middleware\Middleware; -use ZM\Config\ZMConfig; use ZM\Exception\ConfigException; use ZM\Store\FileSystem; use ZM\Utils\HttpUtil; @@ -92,7 +91,7 @@ class AnnotationParser $all_class = FileSystem::getClassesPsr4($path[0], $path[1]); // 读取配置文件中配置的忽略解析的注解名,防止误解析一些别的地方需要的注解,比如@mixin - $conf = ZMConfig::get('global.runtime.annotation_reader_ignore'); + $conf = config('global.runtime.annotation_reader_ignore'); // 有两种方式,第一种是通过名称,第二种是通过命名空间 if (isset($conf['name']) && is_array($conf['name'])) { foreach ($conf['name'] as $v) { diff --git a/src/ZM/Command/CheckConfigCommand.php b/src/ZM/Command/CheckConfigCommand.php index ef49127b..eaec01e2 100644 --- a/src/ZM/Command/CheckConfigCommand.php +++ b/src/ZM/Command/CheckConfigCommand.php @@ -7,7 +7,6 @@ namespace ZM\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use ZM\Config\ZMConfig; class CheckConfigCommand extends Command { @@ -57,7 +56,7 @@ class CheckConfigCommand extends Command { $local_file = include_once WORKING_DIR . '/config/' . $local; if ($local_file === true) { - $local_file = ZMConfig::get('global'); + $local_file = config('global'); } foreach ($remote as $k => $v) { if (!isset($local_file[$k])) { diff --git a/src/ZM/Command/Generate/SystemdGenerateCommand.php b/src/ZM/Command/Generate/SystemdGenerateCommand.php index 6de2711a..851f9ca1 100644 --- a/src/ZM/Command/Generate/SystemdGenerateCommand.php +++ b/src/ZM/Command/Generate/SystemdGenerateCommand.php @@ -7,7 +7,6 @@ namespace ZM\Command\Generate; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use ZM\Config\ZMConfig; class SystemdGenerateCommand extends Command { @@ -21,7 +20,7 @@ class SystemdGenerateCommand extends Command protected function execute(InputInterface $input, OutputInterface $output): int { - ZMConfig::setDirectory(SOURCE_ROOT_DIR . '/config'); + config()->addConfigPath(SOURCE_ROOT_DIR . '/config'); $path = $this->generate(); $output->writeln('成功生成 systemd 文件,位置:' . $path . ''); $output->writeln('有关如何使用 systemd 配置文件,请访问 `https://github.com/zhamao-robot/zhamao-framework/issues/36`'); diff --git a/src/ZM/Config/ZMConfig.php b/src/ZM/Config/ZMConfig.php index 73780924..3b759ffc 100644 --- a/src/ZM/Config/ZMConfig.php +++ b/src/ZM/Config/ZMConfig.php @@ -7,7 +7,7 @@ namespace ZM\Config; use OneBot\V12\Config\Config; use ZM\Exception\ConfigException; -class ZMConfig +class ZMConfig implements \ArrayAccess { /** * @var array 支持的文件扩展名 @@ -55,6 +55,33 @@ class ZMConfig $this->loadFiles(); } + /** + * 添加配置文件路径 + * + * @param string $path 路径 + */ + public function addConfigPath(string $path): void + { + if (!in_array($path, $this->config_paths, true)) { + $this->config_paths[] = $path; + } + } + + /** + * 设置当前环境 + * + * 变更环境后,将会自动调用 `reload` 方法重载配置 + * + * @param string $environment 目标环境 + */ + public function setEnvironment(string $environment): void + { + if ($this->environment !== $environment) { + $this->environment = $environment; + $this->reload(); + } + } + /** * 加载配置文件 * @@ -167,6 +194,26 @@ class ZMConfig $this->loadFiles(); } + public function offsetExists($offset): bool + { + return $this->get($offset) !== null; + } + + public function offsetGet($offset) + { + return $this->get($offset); + } + + public function offsetSet($offset, $value): void + { + $this->set($offset, $value); + } + + public function offsetUnset($offset): void + { + $this->set($offset, null); + } + /** * 获取文件元信息 * diff --git a/src/ZM/Container/ContainerServicesProvider.php b/src/ZM/Container/ContainerServicesProvider.php index 7a80df07..1f2c5ad3 100644 --- a/src/ZM/Container/ContainerServicesProvider.php +++ b/src/ZM/Container/ContainerServicesProvider.php @@ -29,7 +29,7 @@ class ContainerServicesProvider * connection: open, close, message * ``` * - * @param string $scope 作用域 + * @param string $scope 作用域 * @throws ConfigException */ public function registerServices(string $scope, ...$params): void @@ -72,7 +72,7 @@ class ContainerServicesProvider $container->instance('path.working', WORKING_DIR); $container->instance('path.source', SOURCE_ROOT_DIR); $container->alias('path.source', 'path.base'); - $container->instance('path.data', ZMConfig::get('global.data_dir')); + $container->instance('path.data', config('global.data_dir')); $container->instance('path.framework', FRAMEWORK_ROOT_DIR); // 注册worker和驱动 diff --git a/src/ZM/Event/Listener/MasterEventListener.php b/src/ZM/Event/Listener/MasterEventListener.php index 6ecd585a..8e6be230 100644 --- a/src/ZM/Event/Listener/MasterEventListener.php +++ b/src/ZM/Event/Listener/MasterEventListener.php @@ -7,7 +7,6 @@ namespace ZM\Event\Listener; use OneBot\Driver\Workerman\Worker; use OneBot\Util\Singleton; use Swoole\Server; -use ZM\Config\ZMConfig; use ZM\Exception\ZMKnownException; use ZM\Framework; use ZM\Process\ProcessStateManager; @@ -27,7 +26,7 @@ class MasterEventListener SignalListener::getInstance()->signalMaster(); } ProcessStateManager::saveProcessState(ONEBOT_PROCESS_MASTER, $server->master_pid, [ - 'stdout' => ZMConfig::get('global.swoole_options.swoole_set.log_file'), + 'stdout' => config('global.swoole_options.swoole_set.log_file'), 'daemon' => (bool) Framework::getInstance()->getArgv()['daemon'], ]); }); diff --git a/src/ZM/Event/Listener/WorkerEventListener.php b/src/ZM/Event/Listener/WorkerEventListener.php index c275648d..dfd09c91 100644 --- a/src/ZM/Event/Listener/WorkerEventListener.php +++ b/src/ZM/Event/Listener/WorkerEventListener.php @@ -11,7 +11,6 @@ use ZM\Annotation\AnnotationHandler; use ZM\Annotation\AnnotationMap; use ZM\Annotation\AnnotationParser; use ZM\Annotation\Framework\Init; -use ZM\Config\ZMConfig; use ZM\Container\ContainerServicesProvider; use ZM\Exception\ConfigException; use ZM\Exception\ZMKnownException; @@ -159,7 +158,7 @@ class WorkerEventListener } // 读取 MySQL 配置文件 - $conf = ZMConfig::get('global.mysql'); + $conf = config('global.mysql'); if (is_array($conf) && !is_assoc_array($conf)) { // 如果有多个数据库连接,则遍历 foreach ($conf as $conn_conf) { diff --git a/src/ZM/Framework.php b/src/ZM/Framework.php index 33b0ff08..7fde6191 100644 --- a/src/ZM/Framework.php +++ b/src/ZM/Framework.php @@ -19,7 +19,6 @@ use OneBot\Driver\Workerman\WorkermanDriver; use OneBot\Util\Singleton; use Phar; use ZM\Command\Server\ServerStartCommand; -use ZM\Config\ZMConfig; use ZM\Event\EventProvider; use ZM\Event\Listener\HttpEventListener; use ZM\Event\Listener\ManagerEventListener; @@ -189,8 +188,8 @@ class Framework } foreach ($find_dir as $v) { if (is_dir($v)) { - ZMConfig::setDirectory($v); - ZMConfig::setEnv($this->argv['env'] = $this->argv['env'] ?? 'development'); + config()->addConfigPath($v); + config()->setEnvironment($this->argv['env'] = ($this->argv['env'] ?? 'development')); $config_done = true; break; } @@ -214,7 +213,7 @@ class Framework $ob_event_provider = EventProvider::getInstance(); // 初始化时区,默认为上海时区 - date_default_timezone_set(ZMConfig::get('global.runtime.timezone')); + date_default_timezone_set(config('global.runtime.timezone')); // 注册全局错误处理器 set_error_handler(static function ($error_no, $error_msg, $error_file, $error_line) { @@ -251,20 +250,20 @@ class Framework */ public function initDriver() { - switch ($driver = ZMConfig::get('global.driver')) { + switch ($driver = config('global.driver')) { case 'swoole': if (DIRECTORY_SEPARATOR === '\\') { logger()->emergency('Windows does not support swoole driver!'); exit(1); } - ZMConfig::$config['global']['swoole_options']['driver_init_policy'] = DriverInitPolicy::MULTI_PROCESS_INIT_IN_MASTER; - $this->driver = new SwooleDriver(ZMConfig::get('global.swoole_options')); - $this->driver->initDriverProtocols(ZMConfig::get('global.servers')); + config(['global.swoole_options.driver_init_policy' => DriverInitPolicy::MULTI_PROCESS_INIT_IN_MASTER]); + $this->driver = new SwooleDriver(config('global.swoole_options')); + $this->driver->initDriverProtocols(config('global.servers')); break; case 'workerman': - ZMConfig::$config['global']['workerman_options']['driver_init_policy'] = DriverInitPolicy::MULTI_PROCESS_INIT_IN_MASTER; - $this->driver = new WorkermanDriver(ZMConfig::get('global.workerman_options')); - $this->driver->initDriverProtocols(ZMConfig::get('global.servers')); + config(['global.workerman_options.driver_init_policy' => DriverInitPolicy::MULTI_PROCESS_INIT_IN_MASTER]); + $this->driver = new WorkermanDriver(config('global.workerman_options')); + $this->driver->initDriverProtocols(config('global.servers')); break; default: logger()->error(zm_internal_errcode('E00081') . '未知的驱动类型 ' . $driver . ' !'); @@ -327,9 +326,9 @@ class Framework // 打印环境信息 $properties['environment'] = $this->argv['env']; // 打印驱动 - $properties['driver'] = ZMConfig::get('global.driver'); + $properties['driver'] = config('global.driver'); // 打印logger显示等级 - $properties['log_level'] = $this->argv['log-level'] ?? ZMConfig::get('global', 'log_level') ?? 'info'; + $properties['log_level'] = $this->argv['log-level'] ?? config('global', 'log_level') ?? 'info'; // 打印框架版本 $properties['version'] = self::VERSION . (LOAD_MODE === 0 ? (' (build ' . ZM_VERSION_ID . ')') : ''); // 打印 PHP 版本 @@ -342,8 +341,8 @@ class Framework if ($this->driver->getName() === 'swoole') { $properties['process_mode'] = 'MST1'; ProcessStateManager::$process_mode['master'] = 1; - if (ZMConfig::get('global.swoole_options.swoole_server_mode') === SWOOLE_BASE) { - $worker_num = ZMConfig::get('global.swoole_options.swoole_set.worker_num'); + if (config('global.swoole_options.swoole_server_mode') === SWOOLE_BASE) { + $worker_num = config('global.swoole_options.swoole_set.worker_num'); if ($worker_num === null || $worker_num === 1) { $properties['process_mode'] .= 'MAN0#0'; ProcessStateManager::$process_mode['manager'] = 0; @@ -353,12 +352,12 @@ class Framework ProcessStateManager::$process_mode['manager'] = 0; ProcessStateManager::$process_mode['worker'] = swoole_cpu_num(); } else { - $properties['process_mode'] .= 'MAN0#' . ($worker = ZMConfig::get('global.swoole_options.swoole_set.worker_num') ?? swoole_cpu_num()); + $properties['process_mode'] .= 'MAN0#' . ($worker = config('global.swoole_options.swoole_set.worker_num') ?? swoole_cpu_num()); ProcessStateManager::$process_mode['manager'] = 0; ProcessStateManager::$process_mode['worker'] = $worker; } } else { - $worker = ZMConfig::get('global.swoole_options.swoole_set.worker_num') === 0 ? swoole_cpu_num() : ZMConfig::get('global.swoole_options.swoole_set.worker_num') ?? swoole_cpu_num(); + $worker = config('global.swoole_options.swoole_set.worker_num') === 0 ? swoole_cpu_num() : config('global.swoole_options.swoole_set.worker_num') ?? swoole_cpu_num(); $properties['process_mode'] .= 'MAN1#' . $worker; ProcessStateManager::$process_mode['manager'] = 1; ProcessStateManager::$process_mode['worker'] = $worker; @@ -366,7 +365,7 @@ class Framework } elseif ($this->driver->getName() === 'workerman') { $properties['process_mode'] = 'MST1'; ProcessStateManager::$process_mode['master'] = 1; - $worker_num = ZMConfig::get('global.workerman_options.workerman_worker_num'); + $worker_num = config('global.workerman_options.workerman_worker_num'); if (DIRECTORY_SEPARATOR === '\\') { $properties['process_mode'] .= '#0'; ProcessStateManager::$process_mode['manager'] = 0; @@ -379,17 +378,17 @@ class Framework } } // 打印监听端口 - foreach (ZMConfig::get('global.servers') as $k => $v) { + foreach (config('global.servers') as $k => $v) { $properties['listen_' . $k] = $v['type'] . '://' . $v['host'] . ':' . $v['port']; } // 打印 MySQL 连接信息 - if ((ZMConfig::get('global.mysql_config.host') ?? '') !== '') { - $conf = ZMConfig::get('global', 'mysql_config'); + if ((config('global.mysql_config.host') ?? '') !== '') { + $conf = config('global', 'mysql_config'); $properties['mysql'] = $conf['dbname'] . '@' . $conf['host'] . ':' . $conf['port']; } // 打印 Redis 连接信息 - if ((ZMConfig::get('global', 'redis_config')['host'] ?? '') !== '') { - $conf = ZMConfig::get('global', 'redis_config'); + if ((config('global', 'redis_config')['host'] ?? '') !== '') { + $conf = config('global', 'redis_config'); $properties['redis_pool'] = $conf['host'] . ':' . $conf['port']; } @@ -480,14 +479,14 @@ class Framework } switch ($x) { case 'driver': // 动态设置驱动类型 - ZMConfig::$config['global']['driver'] = $y; + config()['global']['driver'] = $y; break; case 'worker-num': // 动态设置 Worker 数量 - ZMConfig::$config['global']['swoole_options']['swoole_set']['worker_num'] = intval($y); - ZMConfig::$config['global']['workerman_options']['workerman_worker_num'] = intval($y); + config()['global']['swoole_options']['swoole_set']['worker_num'] = intval($y); + config()['global']['workerman_options']['workerman_worker_num'] = intval($y); break; case 'daemon': // 启动为守护进程 - ZMConfig::$config['global']['swoole_options']['swoole_set']['daemonize'] = 1; + config()['global']['swoole_options']['swoole_set']['daemonize'] = 1; Worker::$daemonize = true; break; } diff --git a/src/ZM/InstantApplication.php b/src/ZM/InstantApplication.php index 6076aee1..74c4e703 100644 --- a/src/ZM/InstantApplication.php +++ b/src/ZM/InstantApplication.php @@ -6,7 +6,6 @@ namespace ZM; use Exception; use ZM\Command\Server\ServerStartCommand; -use ZM\Config\ZMConfig; use ZM\Exception\InitException; use ZM\Plugin\InstantPlugin; @@ -40,7 +39,7 @@ class InstantApplication extends InstantPlugin public function withArgs(array $args): InstantApplication { - $this->args = ZMConfig::smartPatch($this->args, $args); + $this->args = array_replace_recursive($this->args, $args); return $this; } diff --git a/src/ZM/Store/MySQL/MySQLDriver.php b/src/ZM/Store/MySQL/MySQLDriver.php index 2205248e..68815d0b 100644 --- a/src/ZM/Store/MySQL/MySQLDriver.php +++ b/src/ZM/Store/MySQL/MySQLDriver.php @@ -7,7 +7,6 @@ namespace ZM\Store\MySQL; use Doctrine\DBAL\Driver as DoctrineDriver; use Doctrine\DBAL\Platforms\MySqlPlatform; use Doctrine\DBAL\Schema\MySqlSchemaManager; -use ZM\Config\ZMConfig; class MySQLDriver implements DoctrineDriver { @@ -34,7 +33,7 @@ class MySQLDriver implements DoctrineDriver public function getDatabase($conn) { - $conf = ZMConfig::get('global.mysql'); + $conf = config('global.mysql'); if ($conn instanceof MySQLConnection) { foreach ($conf as $v) { diff --git a/src/ZM/Utils/HttpUtil.php b/src/ZM/Utils/HttpUtil.php index d10d0a64..df651c88 100644 --- a/src/ZM/Utils/HttpUtil.php +++ b/src/ZM/Utils/HttpUtil.php @@ -13,7 +13,6 @@ use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouteCollection; -use ZM\Config\ZMConfig; use ZM\Exception\ConfigException; use ZM\Store\FileSystem; @@ -80,13 +79,13 @@ class HttpUtil public static function handleStaticPage(string $uri, array $settings = []): ResponseInterface { // 确定根目录 - $base_dir = $settings['document_root'] ?? ZMConfig::get('global.file_server.document_root'); + $base_dir = $settings['document_root'] ?? config('global.file_server.document_root'); // 将相对路径转换为绝对路径 if (FileSystem::isRelativePath($base_dir)) { $base_dir = SOURCE_ROOT_DIR . '/' . $base_dir; } // 支持默认缺省搜索的文件名(如index.html) - $base_index = $settings['document_index'] ?? ZMConfig::get('global.file_server.document_index'); + $base_index = $settings['document_index'] ?? config('global.file_server.document_index'); if (is_string($base_index)) { $base_index = [$base_index]; } @@ -110,7 +109,7 @@ class HttpUtil logger()->info('[200] ' . $uri); $exp = strtolower(pathinfo($path . $vp)['extension'] ?? 'unknown'); return HttpFactory::getInstance()->createResponse() - ->withAddedHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream') + ->withAddedHeader('Content-Type', config('file_header')[$exp] ?? 'application/octet-stream') ->withBody(HttpFactory::getInstance()->createStream(file_get_contents($path . '/' . $vp))); } } @@ -119,7 +118,7 @@ class HttpUtil logger()->info('[200] ' . $uri); $exp = strtolower(pathinfo($path)['extension'] ?? 'unknown'); return HttpFactory::getInstance()->createResponse() - ->withAddedHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream') + ->withAddedHeader('Content-Type', config('file_header')[$exp] ?? 'application/octet-stream') ->withBody(HttpFactory::getInstance()->createStream(file_get_contents($path))); } } @@ -136,14 +135,14 @@ class HttpUtil public static function handleHttpCodePage(int $code): ResponseInterface { // 获取有没有规定 code page - $code_page = ZMConfig::get('global.file_server.document_code_page')[$code] ?? null; - if ($code_page !== null && !file_exists((ZMConfig::get('global.file_server.document_root') ?? '/not/exist/') . '/' . $code_page)) { + $code_page = config('global.file_server.document_code_page')[$code] ?? null; + if ($code_page !== null && !file_exists((config('global.file_server.document_root') ?? '/not/exist/') . '/' . $code_page)) { $code_page = null; } if ($code_page === null) { return HttpFactory::getInstance()->createResponse($code); } - return HttpFactory::getInstance()->createResponse($code, null, [], file_get_contents(ZMConfig::get('global.file_server.document_root') . '/' . $code_page)); + return HttpFactory::getInstance()->createResponse($code, null, [], file_get_contents(config('global.file_server.document_root') . '/' . $code_page)); } /**