EatHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Module\AppGame\Handler\Pet;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\AppGame\Validations\PetEatValidation;
  5. use App\Module\Pet\Services\PetService;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Uraus\Kku\Request\RequestPetEat;
  10. use Uraus\Kku\Response\ResponsePetEat;
  11. /**
  12. * 处理宠物喂食请求
  13. */
  14. class EatHandler extends BaseHandler
  15. {
  16. /**
  17. * 是否需要登录
  18. *
  19. * @var bool
  20. */
  21. protected bool $need_login = true;
  22. /**
  23. * 处理宠物喂食请求
  24. *
  25. * @param RequestPetEat $data 宠物喂食请求数据
  26. * @return ResponsePetEat 宠物喂食响应
  27. */
  28. public function handle(Message $data): Message
  29. {
  30. // 创建验证对象
  31. $validation = PetEatValidation::makeByProrobufUser($data);
  32. // 验证请求数据
  33. $validation->validated();
  34. // 验证完成
  35. // 获取请求参数
  36. $petId = $validation->getSafe('petId');
  37. $itemId = $validation->getSafe('itemId');
  38. $num = $validation->getSafe('num');
  39. $userId = $this->user_id;
  40. // 创建响应对象
  41. $response = new ResponsePetEat();
  42. try {
  43. // 开启数据库事务
  44. DB::beginTransaction();
  45. // 调用宠物服务进行喂养
  46. $feedResult = PetService::feedPet($userId, $petId, $itemId, $num);
  47. // 不需要设置响应,默认成功的响应
  48. // 提交事务
  49. DB::commit();
  50. } catch (\Exception $e) {
  51. // 回滚事务
  52. DB::rollBack();
  53. // 记录错误日志
  54. Log::error('宠物喂养失败', [
  55. 'user_id' => $userId,
  56. 'pet_id' => $petId,
  57. 'item_id' => $itemId,
  58. 'num' => $num,
  59. 'error' => $e->getMessage()
  60. ]);
  61. throw $e;
  62. }
  63. return $response;
  64. }
  65. }