GetHandler.php 7.2 KB

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