同步更新

This commit is contained in:
2026-01-13 17:27:32 +08:00
parent 45785dd33f
commit 5d6e2fc5e0
38 changed files with 1211 additions and 305 deletions

View File

@@ -10,13 +10,17 @@
// +----------------------------------------------------------------------
namespace think\console\command\optimize;
use InvalidArgumentException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use Throwable;
class Config extends Command
{
use Discoverable;
protected function configure()
{
$this->setName('optimize:config')
@@ -26,39 +30,54 @@ class Config extends Command
protected function execute(Input $input, Output $output)
{
// 加载配置文件
$dir = $input->getArgument('dir') ?: '';
$path = $this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . ($dir ? $dir . DIRECTORY_SEPARATOR : '');
if (!is_dir($path)) {
$dirs = ((array) $input->getArgument('dir')) ?: $this->getDefaultDirs();
foreach ($dirs as $dir) {
$path = $this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR . ($dir ? $dir . DIRECTORY_SEPARATOR : '');
try {
mkdir($path, 0755, true);
} catch (\Exception $e) {
// 创建失败
$cache = $this->buildCache($dir);
if (! is_dir($path)) {
mkdir($path, 0755, true);
}
file_put_contents($path . 'config.php', $cache);
} catch (Throwable $e) {
$output->warning($e->getMessage());
}
}
$file = $path . 'config.php';
$config = $this->loadConfig($dir);
$content = '<?php ' . PHP_EOL . 'return ' . var_export($config, true) . ';';
if (file_put_contents($file, $content)) {
$output->writeln("<info>Succeed!</info>");
} else {
$output->writeln("<error>config build fail</error>");
}
$output->info('Succeed!');
}
public function loadConfig($dir = '')
private function buildCache(?string $dir = null): string
{
$configPath = $this->app->getRootPath() . ($dir ? 'app' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR : '') . 'config' . DIRECTORY_SEPARATOR;
$files = [];
if (is_dir($configPath)) {
$files = glob($configPath . '*' . $this->app->getConfigExt());
$path = $this->app->getRootPath() . ($dir ? 'app' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR : '') . 'config' . DIRECTORY_SEPARATOR;
if (! is_dir($path)) {
throw new InvalidArgumentException("{$path} directory does not exist");
}
foreach ($files as $file) {
$this->app->config->load($file, pathinfo($file, PATHINFO_FILENAME));
// 使用 clone 防止多应用配置污染
$config = clone $this->app->config;
if (is_dir($path)) {
$files = glob($path . '*' . $this->app->getConfigExt());
foreach ($files as $file) {
$config->load($file, pathinfo($file, PATHINFO_FILENAME));
}
}
return $this->app->config->get();
}
return '<?php ' . PHP_EOL . 'return ' . var_export($config->get(), true) . ';';
}
/**
* 获取默认目录名
* @return array<int, ?string>
*/
private function getDefaultDirs(): array
{
// 包含全局应用配置目录
$dirs = [null];
if ($this->isInstalledMultiApp()) {
$dirs = array_merge($dirs, $this->discoveryMultiAppDirs('config'));
}
return $dirs;
}
}