GetHandler.php 5.1 KB

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