Преглед изворни кода

优化合成Validation逻辑,移除旧版残留代码

- 修复CraftService中的旧版逻辑残留问题
  - 修复canCraftByUser方法调用的错误键名
  - 修复异常处理和返回值格式
  - 统一使用Res对象进行错误处理

- 创建基于组系统的新验证器
  - 新增CraftConsumeValidator:基于消耗组验证资源是否充足
  - 新增CraftConditionValidator:基于条件组验证合成条件
  - 移除旧版CraftMaterialsValidator

- 优化ItemCraftValidation
  - 使用新的基于组系统的验证器
  - 分离条件验证和消耗验证逻辑
  - 提供更准确的错误信息

- 简化CraftHandler验证逻辑
  - 移除重复的验证逻辑
  - 保留基础参数验证
  - 依赖Service层进行完整验证

这次优化彻底移除了旧版合成系统的残留逻辑,统一使用组系统进行验证,提高了代码的一致性和可维护性。
notfff пре 7 месеци
родитељ
комит
f0b74be900

+ 5 - 10
app/Module/AppGame/Handler/Item/CraftHandler.php

@@ -4,7 +4,7 @@ namespace App\Module\AppGame\Handler\Item;
 
 use App\Module\AppGame\Handler\BaseHandler;
 use App\Module\GameItems\Services\CraftService;
-use App\Module\GameItems\Validations\ItemCraftValidation;
+
 use Google\Protobuf\Internal\Message;
 use Illuminate\Support\Facades\Log;
 use Uraus\Kku\Request\RequestItemCraft;
@@ -45,15 +45,10 @@ class CraftHandler extends BaseHandler
                 $quantity = 1;
             }
 
-            // 先进行验证,避免不必要的事务开销
-            $validation = new ItemCraftValidation([
-                'user_id' => $userId,
-                'recipe_id' => $recipeId,
-                'quantity' => $quantity
-            ]);
-
-            // 验证数据
-            $validation->validated();
+            // 基础参数验证
+            if ($recipeId <= 0) {
+                throw new LogicException("配方ID无效");
+            }
 
             // 调用合成服务(服务内部会处理事务)
             $result = CraftService::craftItem($userId, $recipeId,$quantity, [

+ 6 - 6
app/Module/GameItems/Services/CraftService.php

@@ -46,8 +46,8 @@ class CraftService
 
             // 检查用户是否可以合成该配方
             $canCraft = $recipe->canCraftByUser($userId);
-            if (!$canCraft['ValidateException']) {
-                throw new Exception($canCraft['reason']);
+            if (!$canCraft['can_craft']) {
+                throw new ValidateException($canCraft['reason']);
             }
 
             // 检查消耗组是否存在
@@ -75,8 +75,8 @@ class CraftService
                 $quantity // 使用数量作为倍数
             );
 
-            if (!$consumeResult['success']) {
-                throw new LogicException("消耗失败: " . $consumeResult['message']);
+            if ($consumeResult->error) {
+                throw new LogicException("消耗失败: " . $consumeResult->message);
             }
 
             // 判断合成是否成功(基于配方成功率)
@@ -112,7 +112,7 @@ class CraftService
             $craftLog = new ItemCraftLog([
                 'user_id' => $userId,
                 'recipe_id' => $recipeId,
-                'materials' => $consumeResult['consumed'] ?? [],
+                'materials' => $consumeResult->data['consumed'] ?? [],
                 'result_item_id' => $isSuccess && !empty($rewardItems) ? $rewardItems[0]->targetId : null,
                 'result_instance_id' => null,
                 'result_quantity' => $isSuccess && !empty($rewardItems) ? $rewardItems[0]->quantity : 0,
@@ -148,7 +148,7 @@ class CraftService
                 'trace' => $e->getTraceAsString()
             ]);
 
-            return Res::success('合成失败');
+            return Res::error('合成失败: ' . $e->getMessage());
         }
     }
 

+ 10 - 4
app/Module/GameItems/Validations/ItemCraftValidation.php

@@ -3,7 +3,8 @@
 namespace App\Module\GameItems\Validations;
 
 use App\Module\GameItems\Validators\CraftRecipeValidator;
-use App\Module\GameItems\Validators\CraftMaterialsValidator;
+use App\Module\GameItems\Validators\CraftConsumeValidator;
+use App\Module\GameItems\Validators\CraftConditionValidator;
 use UCore\ValidationCore;
 
 /**
@@ -36,10 +37,15 @@ class ItemCraftValidation extends ValidationCore
                 'recipe_id', new CraftRecipeValidator($this, ['recipe']),
                 'msg' => '配方验证失败'
             ],
-            // 验证合成材料是否充
+            // 验证合成条件是否满
             [
-                'recipe_id', new CraftMaterialsValidator($this, ['user_id', 'quantity', 'recipe']),
-                'msg' => '合成材料不足'
+                'recipe_id', new CraftConditionValidator($this, ['user_id', 'recipe']),
+                'msg' => '合成条件不满足'
+            ],
+            // 验证合成消耗是否充足
+            [
+                'recipe_id', new CraftConsumeValidator($this, ['user_id', 'quantity', 'recipe']),
+                'msg' => '合成消耗不足'
             ]
         ];
     }

+ 56 - 0
app/Module/GameItems/Validators/CraftConditionValidator.php

@@ -0,0 +1,56 @@
+<?php
+
+namespace App\Module\GameItems\Validators;
+
+use App\Module\Game\Services\ConditionService;
+use UCore\Validator;
+
+/**
+ * 合成条件验证器
+ * 
+ * 基于组系统验证用户是否满足合成条件
+ */
+class CraftConditionValidator extends Validator
+{
+    /**
+     * 验证合成条件
+     *
+     * @param mixed $value 配方ID
+     * @param array $data 包含用户ID的数组
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        // 从 args 获取参数键名
+        $userIdKey = $this->args[0] ?? 'user_id';
+        $recipeKey = $this->args[1] ?? 'recipe';
+
+        $userId = $data[$userIdKey] ?? null;
+        $recipe = $this->validation->$recipeKey ?? null;
+
+        if (!$userId || !$recipe) {
+            $this->addError('验证合成条件时缺少必要参数');
+            return false;
+        }
+
+        // 如果配方没有条件组,则直接通过
+        if (!$recipe->condition_group_id) {
+            return true;
+        }
+
+        try {
+            // 使用条件组服务检查条件
+            $checkResult = ConditionService::checkCondition($userId, $recipe->condition_group_id);
+            
+            if (!$checkResult['success']) {
+                $this->addError($checkResult['message']);
+                return false;
+            }
+
+            return true;
+        } catch (\Exception $e) {
+            $this->addError('验证合成条件时发生错误: ' . $e->getMessage());
+            return false;
+        }
+    }
+}

+ 59 - 0
app/Module/GameItems/Validators/CraftConsumeValidator.php

@@ -0,0 +1,59 @@
+<?php
+
+namespace App\Module\GameItems\Validators;
+
+use App\Module\Game\Services\ConsumeService;
+use UCore\Validator;
+
+/**
+ * 合成消耗验证器
+ * 
+ * 基于组系统验证用户是否有足够的资源进行合成
+ */
+class CraftConsumeValidator extends Validator
+{
+    /**
+     * 验证合成消耗
+     *
+     * @param mixed $value 配方ID
+     * @param array $data 包含用户ID和数量的数组
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        // 从 args 获取参数键名
+        $userIdKey = $this->args[0] ?? 'user_id';
+        $quantityKey = $this->args[1] ?? 'quantity';
+        $recipeKey = $this->args[2] ?? 'recipe';
+
+        $userId = $data[$userIdKey] ?? null;
+        $quantity = $data[$quantityKey] ?? 1;
+        $recipe = $this->validation->$recipeKey ?? null;
+
+        if (!$userId || !$recipe) {
+            $this->addError('验证合成消耗时缺少必要参数');
+            return false;
+        }
+
+        // 检查配方是否有消耗组
+        if (!$recipe->consume_group_id) {
+            $this->addError('配方未配置消耗组');
+            return false;
+        }
+
+        try {
+            // 使用消耗组服务检查消耗条件
+            $checkResult = ConsumeService::checkConsume($userId, $recipe->consume_group_id, $quantity);
+
+            if (!$checkResult->success) {
+                $this->addError($checkResult->message);
+                return false;
+            }
+
+            return true;
+        } catch (\Exception $e) {
+            $this->addError('验证合成消耗时发生错误: ' . $e->getMessage());
+            return false;
+        }
+    }
+}

+ 0 - 60
app/Module/GameItems/Validators/CraftMaterialsValidator.php

@@ -1,60 +0,0 @@
-<?php
-
-namespace App\Module\GameItems\Validators;
-
-use App\Module\GameItems\Services\ItemService;
-use UCore\Validator;
-
-/**
- * 合成材料验证器
- * 
- * 验证用户是否有足够的材料进行合成
- */
-class CraftMaterialsValidator extends Validator
-{
-    /**
-     * 验证合成材料
-     *
-     * @param mixed $value 配方ID
-     * @param array $data 包含用户ID和数量的数组
-     * @return bool 验证是否通过
-     */
-    public function validate(mixed $value, array $data): bool
-    {
-        // 从 args 获取参数键名
-        $userIdKey = $this->args[0] ?? 'user_id';
-        $quantityKey = $this->args[1] ?? 'quantity';
-        $recipeKey = $this->args[2] ?? 'recipe';
-
-        $userId = $data[$userIdKey] ?? null;
-        $quantity = $data[$quantityKey] ?? 1;
-        $recipe = $this->validation->$recipeKey ?? null;
-
-        if (!$userId || !$recipe) {
-            $this->addError('验证合成材料时缺少必要参数');
-            return false;
-        }
-
-        try {
-            // 检查每个材料是否充足
-            foreach ($recipe->materials as $material) {
-                $requiredQuantity = $material->quantity * $quantity;
-                
-                // 获取用户拥有的该物品数量
-                $userItems = ItemService::getUserItems($userId, ['item_id' => $material->item_id]);
-                $totalQuantity = $userItems->sum('quantity');
-
-                if ($totalQuantity < $requiredQuantity) {
-                    $itemName = $material->item->name ?? "物品ID:{$material->item_id}";
-                    $this->addError("材料不足:{$itemName},需要{$requiredQuantity}个,当前拥有{$totalQuantity}个");
-                    return false;
-                }
-            }
-
-            return true;
-        } catch (\Exception $e) {
-            $this->addError('验证合成材料时发生错误: ' . $e->getMessage());
-            return false;
-        }
-    }
-}