Эх сурвалжийг харах

feat(system): 添加SQL调试功能支持

- 新增DebugHook类用于注册SQL调试中间件
- 创建AppendSqlDebugMiddleware中间件捕获SQL执行日志
- 在响应数据中附加SQL执行记录列表
- 仅在调试模式下启用SQL调试功能
- 实现SQL日志收集和响应注入机制
runphp 1 сар өмнө
parent
commit
a4733edb74

+ 9 - 1
src/Extension.php

@@ -7,6 +7,7 @@ use SixShop\Core\ExtensionAbstract;
 use SixShop\Core\Service\AutoloadService;
 use SixShop\System\Cron\SystemCron;
 use SixShop\System\Enum\ExtensionStatusEnum;
+use SixShop\System\Hook\DebugHook;
 use SixShop\System\Hook\ExtensionStatusHook;
 use SixShop\System\Hook\GatheringCrontabEventHook;
 use SixShop\System\Service\FrontendDeployService;
@@ -24,10 +25,17 @@ class Extension extends ExtensionAbstract
 
     public function getHooks(): array
     {
-        return [
+        $hooks = [
             ExtensionStatusHook::class,
             GatheringCrontabEventHook::class
         ];
+
+        // Debug 模式下添加 DebugHook
+        if (app()->isDebug()) {
+            $hooks[] = DebugHook::class;
+        }
+
+        return $hooks;
     }
 
     public function getCronJobs(): array

+ 23 - 0
src/Hook/DebugHook.php

@@ -0,0 +1,23 @@
+<?php
+declare(strict_types=1);
+
+namespace SixShop\System\Hook;
+
+use SixShop\Core\Attribute\Hook;
+use SixShop\System\Middleware\AppendSqlDebugMiddleware;
+use think\App;
+use think\event\HttpRun;
+
+class DebugHook
+{
+
+    public function __construct(private App $app)
+    {
+
+    }
+    #[Hook(HttpRun::class)]
+    public function appendSqlDebug(): void
+    {
+        $this->app->middleware->add(AppendSqlDebugMiddleware::class);
+    }
+}

+ 35 - 0
src/Middleware/AppendSqlDebugMiddleware.php

@@ -0,0 +1,35 @@
+<?php
+declare(strict_types=1);
+
+namespace SixShop\System\Middleware;
+
+use Closure;
+use think\DbManager;
+use think\Request;
+use think\Response;
+
+
+class AppendSqlDebugMiddleware
+{
+    private array $logList = [];
+
+    public function __construct(private readonly DbManager $dbManager)
+    {
+        $this->dbManager->setLog(function (string $type, string $log) {
+            $this->logList[] = $log;
+        });
+    }
+
+    public function handle(Request $request, Closure $next): Response
+    {
+        $response = $next($request);
+        if ($response instanceof Response && is_array($data = $response->getData())) {
+            $data['sql'] = $this->logList;
+            if (!empty($data['sql'])) {
+                $response->data($data);
+            }
+        }
+
+        return $response;
+    }
+}