Преглед на файлове

refactor(core): 优化核心服务类并改进异常处理

- 使用 readonly 关键字增强 AutoloadService、CommandService 和 RegisterRouteService 类型安全性
- 统一异常类型引用方式,移除反斜杠前缀,提高代码一致性
- 添加缺失的 use 声明以支持新的异常和反射类引用
- 简化 Helper 类中的逻辑异常抛出方法调用
- 移除 build_tree_options 方法实现,委托给全局函数处理
- 更新 ExtensionAbstract 中的异常抛出语法
- 在多个服务方法上添加适当的注解文档块说明可能抛出的异常类型
- 修正 CoreService 中对扩展名列表的访问方式,使用全局函数替代静态属性
- 改进 Plugin 类中运行时异常的创建方式
runphp преди 3 месеца
родител
ревизия
7ca10a2740

+ 5 - 1
src/ExtensionAbstract.php

@@ -3,6 +3,7 @@ declare(strict_types=1);
 
 namespace SixShop\Core;
 
+use Exception;
 use SixShop\Core\Contracts\ExtensionInterface;
 use think\helper\Macroable;
 
@@ -17,11 +18,14 @@ abstract class ExtensionAbstract implements ExtensionInterface
 
     protected bool $isBooted = false;
 
+    /**
+     * @throws Exception
+     */
     public function getInfo(): array
     {
         if (empty($this->info)) {
             if (!file_exists($this->getBaseDir() . '/info.php')) {
-                throw new \Exception('Extension info file not found, please check the extension directory and info.php file.');
+                throw new Exception('Extension info file not found, please check the extension directory and info.php file.');
             }
             $this->info = require $this->getBaseDir() . '/info.php';
         }

+ 5 - 33
src/Helper.php

@@ -3,8 +3,8 @@ declare(strict_types=1);
 
 namespace SixShop\Core;
 
+use Random\RandomException;
 use SixShop\Core\Exception\LogicException;
-use SixShop\Core\Service\CoreService;
 use think\Paginator;
 use think\Response;
 
@@ -46,7 +46,7 @@ final class Helper
      */
     public static function throw_logic_exception(string $msg = 'error', int $code = 1, string $status = 'error', mixed $data = [], int $httpCode = 200, $header = [], $options = []): void
     {
-        throw new LogicException(self::error_response($msg, $status, $code, $data, $httpCode, $header, $options));
+        throw new LogicException(error_response($msg, $status, $code, $data, $httpCode, $header, $options));
     }
 
     /**
@@ -85,42 +85,14 @@ final class Helper
         bool   $preserveOriginal = true
     ): array
     {
-        $tree = [];
-        foreach ($data as $item) {
-            if ($item[$parentField] == $parentId) {
-                $node = [
-                    'value' => $item[$valueField],
-                    'label' => $item[$labelField]
-                ];
-
-                // 根据参数决定是否保留原始数据
-                if ($preserveOriginal) {
-                    $node = array_merge($item, $node);
-                }
-
-                $children = self::build_tree_options(
-                    $data,
-                    $valueField,
-                    $labelField,
-                    $parentField,
-                    $item[$valueField],
-                    $childrenKey,
-                    $preserveOriginal // 传递参数到递归调用
-                );
-
-                if ($children) {
-                    $node[$childrenKey] = $children;
-                }
-                $tree[] = $node;
-            }
-        }
-        return $tree;
+       return build_tree_options($data, $valueField, $labelField, $parentField, $parentId, $childrenKey, $preserveOriginal);
     }
 
     /**
      * 生成随机密码
      * @param int $length 密码长度
      * @return string 生成的密码
+     * @throws RandomException
      * @deprecated 函数已弃用, 请使用 secret_password()
      */
     public static function secret_password(int $length = 16): string
@@ -145,6 +117,6 @@ final class Helper
      */
     public static function extension_name_list(): array
     {
-        return CoreService::$extensionNameList;
+        return extension_name_list();
     }
 }

+ 6 - 4
src/Job/BaseJob.php

@@ -4,8 +4,10 @@ declare(strict_types=1);
 namespace SixShop\Core\Job;
 
 use Closure;
+use Exception;
 use think\facade\Log;
 use think\queue\Job;
+use Throwable;
 use function Opis\Closure\{serialize, unserialize};
 
 /**
@@ -72,7 +74,7 @@ abstract class BaseJob
             // 标记任务完成
             $job->delete();
 
-        } catch (\Exception|\Throwable $e) {
+        } catch (Exception|Throwable $e) {
             $this->handleException($job, $data, $e);
         }
     }
@@ -104,9 +106,9 @@ abstract class BaseJob
      *
      * @param Job $job 队列任务对象
      * @param T $data 任务数据
-     * @param \Throwable|\Exception $exception 异常对象
+     * @param Throwable|Exception $exception 异常对象
      */
-    protected function handleException(Job $job, mixed $data, \Throwable|\Exception $exception): void
+    protected function handleException(Job $job, mixed $data, Throwable|Exception $exception): void
     {
         Log::error('队列任务执行异常: ' . static::class . ' - ' . $exception->getMessage().'{data},{trace}', [
             'data' => json_encode($data),
@@ -125,7 +127,7 @@ abstract class BaseJob
             if ($this->enableFailedCallback) {
                 try {
                     $this->onFailed($data);
-                } catch (\Exception $e) {
+                } catch (Exception $e) {
                     Log::error('任务失败回调执行异常: ' . $e->getMessage());
                 }
             }

+ 2 - 1
src/Plugin.php

@@ -10,6 +10,7 @@ use Composer\IO\IOInterface;
 use Composer\Plugin\PluginInterface;
 use Composer\Script\Event;
 use Composer\Script\ScriptEvents;
+use RuntimeException;
 
 class Plugin implements PluginInterface, EventSubscriberInterface
 {
@@ -37,7 +38,7 @@ class Plugin implements PluginInterface, EventSubscriberInterface
         if (file_exists($filePath)) {
             return self::$installedSixShopExtensions = require $filePath;
         }
-        throw new \RuntimeException('Please run "composer dump-autoload" to generate installedSixShop.php');
+        throw new RuntimeException('Please run "composer dump-autoload" to generate installedSixShop.php');
     }
 
     public function activate(Composer $composer, IOInterface $io): void

+ 2 - 2
src/Service/AutoloadService.php

@@ -8,7 +8,7 @@ use think\App;
 use function SixShop\Core\extension_path;
 
 
-class AutoloadService
+readonly class AutoloadService
 {
     public function __construct(private App $app)
     {
@@ -25,7 +25,7 @@ class AutoloadService
             $this->app->bind('extension.' . $extensionID, $composerFile['extra']['sixshop']['class']);
         }
         $extensionPath = extension_path();
-        $classLoader = $this->app->classLoader;
+        $classLoader = $this->app->get('classLoader');
         foreach ($extensionNameList as $moduleName) {
             $dir = $extensionPath . $moduleName;
             if (!file_exists($dir . '/composer.json')) {

+ 3 - 2
src/Service/CommandService.php

@@ -3,16 +3,17 @@ declare(strict_types=1);
 
 namespace SixShop\Core\Service;
 
+use Closure;
 use think\exception\ClassNotFoundException;
 use function SixShop\Core\extension_name_list;
 
-class CommandService
+readonly class CommandService
 {
     public function __construct(private AutoloadService $autoloadService)
     {
     }
 
-    public function init(\Closure $closure): void
+    public function init(Closure $closure): void
     {
         $commands = [];
         foreach (extension_name_list() as $extensionName) {

+ 11 - 0
src/Service/CoreService.php

@@ -5,6 +5,8 @@ namespace SixShop\Core\Service;
 
 use Composer\InstalledVersions;
 use Composer\Json\JsonFile;
+use ReflectionException;
+use Seld\JsonLint\ParsingException;
 use SixShop\Core\Exception\ExceptionHandle;
 use SixShop\Core\Plugin;
 use SixShop\Core\Request;
@@ -32,6 +34,9 @@ class CoreService extends Service
         return self::$extensionComposerMap;
     }
 
+    /**
+     * @throws ParsingException
+     */
     public function register(): void
     {
         $this->app->bind(Handle::class, ExceptionHandle::class);
@@ -43,6 +48,9 @@ class CoreService extends Service
         $this->compatibleExtensionNameList();
     }
 
+    /**
+     * @throws ParsingException
+     */
     private function initExtensionList(): void
     {
         if (!empty(self::$extensionComposerMap)) {
@@ -94,6 +102,9 @@ class CoreService extends Service
         }
     }
 
+    /**
+     * @throws ReflectionException
+     */
     public function boot(): void
     {
         $autoloadService = $this->app->make(AutoloadService::class);

+ 4 - 0
src/Service/HookAttributeService.php

@@ -4,6 +4,7 @@ declare(strict_types=1);
 namespace SixShop\Core\Service;
 
 use ReflectionClass;
+use ReflectionException;
 use ReflectionMethod;
 use SixShop\Core\Attribute\Hook;
 use think\Event;
@@ -16,6 +17,9 @@ readonly class HookAttributeService
     {
     }
 
+    /**
+     * @throws ReflectionException
+     */
     public function init(): void
     {
         foreach (extension_name_list() as $extensionName) {

+ 3 - 2
src/Service/RegisterRouteService.php

@@ -3,19 +3,20 @@ declare(strict_types=1);
 
 namespace SixShop\Core\Service;
 
+use Closure;
 use SixShop\Core\Event\BeforeRegisterRouteEvent;
 use think\facade\Event;
 use think\facade\Route;
 use think\Http;
 use function SixShop\Core\extension_name_list;
 
-class RegisterRouteService
+readonly class RegisterRouteService
 {
     public function __construct(private AutoloadService $autoloadService, private Http $http)
     {
     }
 
-    public function init(): \Closure
+    public function init(): Closure
     {
         return function () {
             $appName = $this->http->getName();