GetHandler.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. <?php
  2. namespace App\Module\AppGame\Handler\Pet;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\GameItems\Services\ItemService;
  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\RequestPetGet;
  10. use Uraus\Kku\Response\ResponsePetGet;
  11. use Uraus\Kku\Common\RESPONSE_CODE;
  12. use UCore\Exception\LogicException;
  13. /**
  14. * 处理通过物品获取宠物请求
  15. */
  16. class GetHandler extends BaseHandler
  17. {
  18. /**
  19. * 是否需要登录
  20. * @var bool
  21. */
  22. protected bool $need_login = true;
  23. /**
  24. * 处理通过物品获取宠物请求
  25. *
  26. * @param RequestPetGet $data 获取宠物请求数据
  27. * @return ResponsePetGet 获取宠物响应
  28. */
  29. public function handle(Message $data): Message
  30. {
  31. // 创建响应对象
  32. $response = new ResponsePetGet();
  33. try {
  34. // 获取请求参数
  35. $itemId = $data->getItemId();
  36. $userId = $this->user_id;
  37. // 验证参数
  38. if (!$itemId || $itemId <= 0) {
  39. throw new LogicException("物品ID无效");
  40. }
  41. // 先进行验证,避免不必要的事务开销
  42. $validation = new \App\Module\Pet\Validations\PetGetValidation([
  43. 'user_id' => $userId,
  44. 'item_id' => $itemId
  45. ]);
  46. // 验证数据
  47. $validation->validated();
  48. // 验证通过后,开启事务
  49. DB::beginTransaction();
  50. // 执行业务逻辑(不再需要验证)
  51. $result = $this->createPetFromItem($userId, $itemId);
  52. // 提交事务
  53. DB::commit();
  54. // 设置响应状态
  55. $this->response->setCode(RESPONSE_CODE::OK);
  56. $this->response->setMsg($result['message']);
  57. } catch (\Exception $e) {
  58. // 系统异常,需要回滚事务
  59. if (DB::transactionLevel() > 0) {
  60. DB::rollBack();
  61. }
  62. Log::error('获取宠物操作异常', [
  63. 'user_id' => $userId ?? $this->user_id,
  64. 'item_id' => $itemId ?? null,
  65. 'error' => $e->getMessage(),
  66. 'trace' => $e->getTraceAsString()
  67. ]);
  68. // 重新抛出异常,交由框架处理
  69. throw $e;
  70. }
  71. return $response;
  72. }
  73. /**
  74. * 通过物品创建宠物
  75. *
  76. * @param int $userId 用户ID
  77. * @param int $itemId 物品ID
  78. * @return array 创建结果
  79. * @throws LogicException
  80. */
  81. private function createPetFromItem(int $userId, int $itemId): array
  82. {
  83. // 防错误机制:获取物品的宠物种类属性
  84. $petType = ItemService::getItemNumericAttribute($itemId, 'pet_type');
  85. // 防错误机制:基本检查,避免意外执行
  86. if (empty($petType)) {
  87. Log::warning('物品没有宠物种类属性,但继续执行', [
  88. 'user_id' => $userId,
  89. 'item_id' => $itemId,
  90. 'pet_type' => $petType
  91. ]);
  92. throw new LogicException("该物品不能获取宠物");
  93. }
  94. // 消耗物品
  95. ItemService::consumeItem($userId, $itemId, null, 1, [
  96. 'source_type' => 'pet_get',
  97. 'source_id' => 0,
  98. 'details' => [
  99. 'pet_type' => $petType,
  100. 'action' => 'create_pet_from_item'
  101. ]
  102. ]);
  103. // 生成宠物名称(可以根据宠物种类生成默认名称)
  104. $petName = $this->generatePetName($petType);
  105. // 创建宠物
  106. $result = PetService::createPet($userId, $petName, null, [
  107. 'pet_type' => $petType,
  108. 'source' => 'item_use',
  109. 'source_item_id' => $itemId
  110. ]);
  111. if (!$result['success']) {
  112. throw new LogicException("宠物创建失败: " . ($result['message'] ?? '未知错误'));
  113. }
  114. // 记录日志
  115. Log::info('用户通过物品获取宠物成功', [
  116. 'user_id' => $userId,
  117. 'item_id' => $itemId,
  118. 'pet_type' => $petType,
  119. 'pet_id' => $result['pet_id'],
  120. 'pet_name' => $petName,
  121. 'pet_grade' => $result['grade']
  122. ]);
  123. return [
  124. 'message' => '恭喜您获得了新宠物:' . $petName,
  125. 'pet_id' => $result['pet_id'],
  126. 'pet_name' => $petName,
  127. 'pet_type' => $petType,
  128. 'pet_grade' => $result['grade']
  129. ];
  130. }
  131. /**
  132. * 生成宠物名称
  133. *
  134. * @param string $petType 宠物种类
  135. * @return string 宠物名称
  136. */
  137. private function generatePetName(string $petType): string
  138. {
  139. // 根据宠物种类生成默认名称
  140. $nameMap = [
  141. 'dog' => '小狗',
  142. 'cat' => '小猫',
  143. 'bird' => '小鸟',
  144. 'fish' => '小鱼',
  145. 'rabbit' => '小兔',
  146. 'hamster' => '小仓鼠',
  147. ];
  148. $baseName = $nameMap[$petType] ?? '小宠物';
  149. // 添加随机后缀以避免重名
  150. $suffix = rand(1000, 9999);
  151. return $baseName . $suffix;
  152. }
  153. }