Przeglądaj źródła

refactor(pet): 重构宠物喂食功能

- 新增 PetEatValidation 类用于验证宠物喂食请求参数
- 添加 PetExistsValidator 和 PetStatusValidator 用于验证宠物存在性和状态
- 修改 PetFoodValidator 以使用 ItemService
- 移除 PetFeedValidator 类- 更新 EatHandler 中的逻辑,使用新的验证器进行参数校验
- 增加事务处理和日志记录
Your Name 8 miesięcy temu
rodzic
commit
6a26cd3a25

+ 16 - 0
UCore/Validator.php

@@ -52,4 +52,20 @@ abstract class Validator extends AbstractValidator
     }
 
 
+    /**
+     * 增加一个模板的错误消息,并返回False
+     * @param $value
+     * @param string $message 消息模版
+     * @param string $msg
+     * @return mixed
+     * 
+     */
+    public function addErrorTpl($p, $msgTpl, $field = '')
+    {
+        //        dd(strtr($msgTpl, $p),$msgTpl,$p);
+        $this->validation->addError($field, strtr($msgTpl, $p));
+
+        return false;
+    }
+
 }

+ 0 - 29
UCore/Validator/ValidationMessage.php

@@ -1,29 +0,0 @@
-<?php
-
-namespace UCore\Validator;
-
-
-
-use UCore\Exception\ValidateException;
-
-trait ValidationMessage
-{
-
-
-    /**
-     * 抛出验证错误的异常
-     * @param $value
-     * @param string $message 消息模版
-     * @param string $msg
-     * @return mixed
-     * @throws ValidateException
-     */
-    public function throwMessage($p, $msgTpl)
-    {
-//        dd(strtr($msgTpl, $p),$msgTpl,$p);
-        throw new ValidateException($this->validation, strtr($msgTpl, $p));
-
-
-    }
-
-}

+ 53 - 1
app/Module/AppGame/Handler/Pet/EatHandler.php

@@ -3,7 +3,11 @@
 namespace App\Module\AppGame\Handler\Pet;
 
 use App\Module\AppGame\Handler\BaseHandler;
+use App\Module\Pet\Services\PetService;
+use App\Module\Pet\Validation\PetEatValidation;
 use Google\Protobuf\Internal\Message;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
 use Uraus\Kku\Request\RequestPetEat;
 use Uraus\Kku\Response\ResponsePetEat;
 
@@ -29,7 +33,55 @@ class EatHandler extends BaseHandler
         // 创建响应对象
         $response = new ResponsePetEat();
 
-        // TODO: 实现具体逻辑
+        try {
+            // 创建验证对象
+            $validation = PetEatValidation::makeByProrobuf($data);
+
+            // 设置用户ID
+            $validation->user_id = $this->user_id;
+
+            // 验证请求数据
+            $validation->validated();
+
+            // 获取验证后的数据
+            $petId = $validation->pet_id;
+            $itemId = $validation->item_id;
+            $amount = $validation->num;
+
+            // 开启事务
+            DB::beginTransaction();
+
+            try {
+                // 调用宠物服务进行喂食
+                $result = PetService::feedPet($this->user_id, $petId, $itemId, $amount);
+
+                // 提交事务
+                DB::commit();
+
+                // 记录日志
+                Log::info('宠物喂食成功', [
+                    'user_id' => $this->user_id,
+                    'pet_id' => $petId,
+                    'item_id' => $itemId,
+                    'amount' => $amount,
+                    'result' => $result
+                ]);
+            } catch (\Exception $e) {
+                // 回滚事务
+                DB::rollBack();
+                throw $e;
+            }
+        } catch (\Exception $e) {
+            // 记录错误日志
+            Log::error('宠物喂食失败', [
+                'user_id' => $this->user_id,
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString()
+            ]);
+
+            // 抛出异常,让框架处理错误响应
+            throw $e;
+        }
 
         return $response;
     }

+ 91 - 0
app/Module/Pet/Validation/PetEatValidation.php

@@ -0,0 +1,91 @@
+<?php
+
+namespace App\Module\Pet\Validation;
+
+use App\Module\Pet\Validators\PetFoodValidator;
+use App\Module\Pet\Validators\PetExistsValidator;
+use App\Module\Pet\Validators\PetStatusValidator;
+use App\Module\Pet\Enums\PetStatus;
+use UCore\ValidationCore;
+
+/**
+ * 宠物喂食验证类
+ *
+ * 用于验证宠物喂食请求的参数
+ */
+class PetEatValidation extends ValidationCore
+{
+    /**
+     * 宠物ID
+     *
+     * @var int
+     */
+    public $pet_id;
+
+    /**
+     * 物品ID
+     *
+     * @var int
+     */
+    public $item_id;
+
+    /**
+     * 数量
+     *
+     * @var int
+     */
+    public $num;
+
+    /**
+     * 用户ID
+     *
+     * @var int
+     */
+    public $user_id;
+
+    /**
+     * 验证规则
+     *
+     * @param array $rules 自定义规则
+     * @return array
+     */
+    public function rules($rules = []): array
+    {
+        return [
+            [
+                'pet_id,item_id,num,user_id', 'required'
+            ],
+            [
+                'pet_id,item_id,num', 'integer', 'min' => 1,
+                'msg' => '{attr}必须是大于0的整数'
+            ],
+            // 验证宠物是否存在
+            [
+                'pet_id', new PetExistsValidator($this),
+                'msg' => '宠物不存在或不属于当前用户'
+            ],
+            // 验证宠物状态是否正常
+            [
+                'pet_id', new PetStatusValidator($this, [PetStatus::NORMAL]),
+                'msg' => '宠物状态不允许喂食'
+            ],
+            // 验证物品是否为宠物口粮
+            [
+                'item_id', new PetFoodValidator($this),
+                'msg' => '该物品不是宠物口粮'
+            ]
+        ];
+    }
+
+    /**
+     * 设置默认值
+     *
+     * @return array
+     */
+    public function default(): array
+    {
+        return [
+            'num' => 1
+        ];
+    }
+}

+ 52 - 0
app/Module/Pet/Validators/PetExistsValidator.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+
+/**
+ * 宠物存在验证器
+ *
+ * 用于验证宠物是否存在
+ */
+class PetExistsValidator extends Validator
+{
+
+
+    /**
+     * 验证方法
+     *
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = (int)$value;
+        $userId = $data['user_id'] ?? 0;
+
+        try {
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->when($userId > 0, function($query) use ($userId) {
+                    return $query->where('user_id', $userId);
+                })
+                ->first();
+
+            if (!$pet) {
+                if ($userId > 0) {
+                    $this->addError('宠物不存在或不属于当前用户');
+                } else {
+                    $this->addError('宠物不存在');
+                }
+                return false;
+            }
+
+            return true;
+        } catch (\Exception $e) {
+            $this->addError('验证过程发生错误: ' . $e->getMessage());
+            return false;
+        }
+    }
+}

+ 0 - 59
app/Module/Pet/Validators/PetFeedValidator.php

@@ -1,59 +0,0 @@
-<?php
-
-namespace App\Module\Pet\Validators;
-
-use App\Module\Pet\Enums\PetStatus;
-use App\Module\Pet\Models\PetUser;
-use UCore\Validator;
-use UCore\Validator\ValidationMessage;
-
-/**
- * 宠物喂养验证器
- * 
- * 用于验证宠物喂养条件的合法性
- */
-class PetFeedValidator extends Validator
-{
-    use ValidationMessage;
-    
-    /**
-     * 验证方法
-     * 
-     * @param mixed $value 宠物ID
-     * @param array $data 所有数据
-     * @return bool 验证是否通过
-     */
-    public function validate(mixed $value, array $data): bool
-    {
-        $petId = $value;
-        $itemId = $data['itemId'] ?? 0;
-        
-        try {
-            // 获取宠物信息
-            $pet = PetUser::find($petId);
-            
-            if (!$pet) {
-                $this->throwMessage([], '宠物不存在');
-                return false;
-            }
-            
-            // 检查宠物状态
-            if ($pet->status !== PetStatus::NORMAL) {
-                $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许喂养');
-                return false;
-            }
-            
-            // 验证物品是否为宠物口粮
-            $petFoodValidator = new PetFoodValidator($this->validation);
-            if (!$petFoodValidator->validate($itemId, [])) {
-                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
-                return false;
-            }
-            
-            return true;
-        } catch (\Exception $e) {
-            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
-            return false;
-        }
-    }
-}

+ 19 - 9
app/Module/Pet/Validators/PetFoodValidator.php

@@ -2,7 +2,7 @@
 
 namespace App\Module\Pet\Validators;
 
-use App\Module\GameItems\Models\Item;
+use App\Module\GameItems\Services\ItemService;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Log;
 use UCore\Validator;
@@ -48,19 +48,22 @@ class PetFoodValidator extends Validator
 
         if ($cachedResult !== null) {
             if (!$cachedResult) {
-                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
+                $this->addError("物品({$itemId})不是宠物口粮");
             }
             return $cachedResult;
         }
 
         try {
+            // 创建物品服务实例
+            $itemService = new ItemService();
+
             // 获取物品信息
-            $item = Item::find($itemId);
+            $item = $itemService->getItemInfo($itemId);
 
             if (!$item) {
                 // 物品不存在
                 Cache::put($cacheKey, false, $this->cacheExpiration);
-                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不存在');
+                $this->addError("物品({$itemId})不存在");
                 return false;
             }
 
@@ -71,7 +74,7 @@ class PetFoodValidator extends Validator
             Cache::put($cacheKey, $isPetFood, $this->cacheExpiration);
 
             if (!$isPetFood) {
-                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
+                $this->addError("物品({$itemId})不是宠物口粮");
             }
 
             return $isPetFood;
@@ -81,7 +84,7 @@ class PetFoodValidator extends Validator
                 'error' => $e->getMessage()
             ]);
 
-            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            $this->addError('验证过程发生错误: ' . $e->getMessage());
             return false;
         }
     }
@@ -89,16 +92,18 @@ class PetFoodValidator extends Validator
     /**
      * 检查物品是否具有宠物口粮属性
      *
-     * @param Item $item 物品对象
+     * @param object|array $item 物品信息
      * @return bool 是否具有宠物口粮属性
      */
-    protected function checkPetFoodAttributes(Item $item): bool
+    protected function checkPetFoodAttributes($item): bool
     {
         // 检查物品是否有pet_power或pet_exp属性
         $numericAttributes = $item->numeric_attributes ?? [];
 
         if (is_string($numericAttributes)) {
             $numericAttributes = json_decode($numericAttributes, true) ?? [];
+        } elseif (is_object($numericAttributes)) {
+            $numericAttributes = (array)$numericAttributes;
         }
 
         // 检查是否有宠物相关属性
@@ -118,8 +123,11 @@ class PetFoodValidator extends Validator
     public function getPetFoodAttributes(int $itemId): array
     {
         try {
+            // 创建物品服务实例
+            $itemService = new ItemService();
+
             // 获取物品信息
-            $item = Item::find($itemId);
+            $item = $itemService->getItemInfo($itemId);
 
             if (!$item) {
                 return [
@@ -133,6 +141,8 @@ class PetFoodValidator extends Validator
 
             if (is_string($numericAttributes)) {
                 $numericAttributes = json_decode($numericAttributes, true) ?? [];
+            } elseif (is_object($numericAttributes)) {
+                $numericAttributes = (array)$numericAttributes;
             }
 
             return [

+ 57 - 0
app/Module/Pet/Validators/PetStatusValidator.php

@@ -0,0 +1,57 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物状态验证器
+ *
+ * 用于验证宠物状态是否允许执行特定操作
+ */
+class PetStatusValidator extends Validator
+{
+    use ValidationMessage;
+
+    /**
+     * 验证方法
+     *
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = (int)$value;
+        $expectedStatus = $this->args[0] ?? PetStatus::NORMAL;
+
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+
+            if (!$pet) {
+                // 宠物不存在的验证应该由 PetExistsValidator 处理
+                // 这里只关注状态验证
+                return true;
+            }
+
+            // 检查宠物状态
+            if ($pet->status !== $expectedStatus) {
+                $statusName = $pet->status->name;
+                $expectedStatusName = $expectedStatus->name;
+
+                $this->addError("宠物当前状态({$statusName})不允许执行此操作,需要状态为({$expectedStatusName})");
+
+                return false;
+            }
+
+            return true;
+        } catch (\Exception $e) {
+            $this->addError('验证过程发生错误: ' . $e->getMessage());
+            return false;
+        }
+    }
+}