| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- <?php
- namespace App\Module\AppGame\Handler\Pet;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\GameItems\Services\ItemService;
- use App\Module\Pet\Services\PetService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Uraus\Kku\Request\RequestPetGet;
- use Uraus\Kku\Response\ResponsePetGet;
- use UCore\Exception\LogicException;
- /**
- * 处理通过物品获取宠物请求
- */
- class GetHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理通过物品获取宠物请求
- *
- * @param RequestPetGet $data 获取宠物请求数据
- * @return ResponsePetGet 获取宠物响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponsePetGet();
- try {
- // 获取请求参数
- $itemId = $data->getItemId();
- $userId = $this->user_id;
- // 验证参数
- if (!$itemId || $itemId <= 0) {
- throw new LogicException("物品ID无效");
- }
- // 先进行验证,避免不必要的事务开销
- $validation = new \App\Module\Pet\Validations\PetGetValidation([
- 'user_id' => $userId,
- 'item_id' => $itemId
- ]);
- // 验证数据
- $validation->validated();
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 执行业务逻辑(不再需要验证)
- $result = $this->createPetFromItem($userId, $itemId);
- // 提交事务
- DB::commit();
- // 设置响应状态
- $this->response->setCode(0);
- $this->response->setMsg($result['message']);
- // 设置LastData
- if (isset($result['last_data'])) {
- $this->response->setLastData($result['last_data']);
- }
- } catch (\UCore\Exception\ValidateException $e) {
- // 验证失败,此时可能还没有开启事务
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('用户获取宠物验证失败', [
- 'user_id' => $userId ?? $this->user_id,
- 'item_id' => $itemId ?? null,
- 'error' => $e->getMessage()
- ]);
- } catch (LogicException $e) {
- // 业务逻辑异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- // 设置错误响应
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('用户获取宠物失败', [
- 'user_id' => $userId ?? $this->user_id,
- 'item_id' => $itemId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- } catch (\Exception $e) {
- // 系统异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- // 设置错误响应
- $this->response->setCode(500);
- $this->response->setMsg('系统错误,请稍后再试');
- Log::error('获取宠物操作异常', [
- 'user_id' => $userId ?? $this->user_id,
- 'item_id' => $itemId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- /**
- * 通过物品创建宠物
- *
- * @param int $userId 用户ID
- * @param int $itemId 物品ID
- * @return array 创建结果
- * @throws LogicException
- */
- private function createPetFromItem(int $userId, int $itemId): array
- {
- // 防错误机制:获取物品的宠物种类属性
- $petType = ItemService::getItemNumericAttribute($itemId, 'pet_type');
- // 防错误机制:基本检查,避免意外执行
- if (empty($petType)) {
- Log::warning('物品没有宠物种类属性,但继续执行', [
- 'user_id' => $userId,
- 'item_id' => $itemId,
- 'pet_type' => $petType
- ]);
- throw new LogicException("该物品不能获取宠物");
- }
- // 消耗物品
- ItemService::consumeItem($userId, $itemId, null, 1, [
- 'source_type' => 'pet_get',
- 'source_id' => 0,
- 'details' => [
- 'pet_type' => $petType,
- 'action' => 'create_pet_from_item'
- ]
- ]);
- // 生成宠物名称(可以根据宠物种类生成默认名称)
- $petName = $this->generatePetName($petType);
- // 创建宠物
- $result = PetService::createPet($userId, $petName, null, [
- 'pet_type' => $petType,
- 'source' => 'item_use',
- 'source_item_id' => $itemId
- ]);
- if (!$result['success']) {
- throw new LogicException("宠物创建失败: " . ($result['message'] ?? '未知错误'));
- }
- // 创建LastData对象,用于返回宠物信息
- $lastData = new \Uraus\Kku\Common\LastData();
- // 获取创建的宠物详细信息(用于日志记录和返回数据)
- try {
- $petData = PetService::getPetStatus($userId, $result['pet_id']);
- // 设置宠物数据到LastData(这里需要根据实际的LastData结构调整)
- // $lastData->setPets([$petData]);
- } catch (\Exception $e) {
- Log::warning('获取宠物详细信息失败,但继续执行', [
- 'user_id' => $userId,
- 'pet_id' => $result['pet_id'],
- 'error' => $e->getMessage()
- ]);
- $petData = null;
- }
- // 记录日志
- Log::info('用户通过物品获取宠物成功', [
- 'user_id' => $userId,
- 'item_id' => $itemId,
- 'pet_type' => $petType,
- 'pet_id' => $result['pet_id'],
- 'pet_name' => $petName,
- 'pet_grade' => $result['grade'],
- 'pet_data_loaded' => $petData !== null
- ]);
- return [
- 'message' => '恭喜您获得了新宠物:' . $petName,
- 'last_data' => $lastData,
- 'pet_id' => $result['pet_id'],
- 'pet_name' => $petName,
- 'pet_type' => $petType,
- 'pet_grade' => $result['grade']
- ];
- }
- /**
- * 生成宠物名称
- *
- * @param string $petType 宠物种类
- * @return string 宠物名称
- */
- private function generatePetName(string $petType): string
- {
- // 根据宠物种类生成默认名称
- $nameMap = [
- 'dog' => '小狗',
- 'cat' => '小猫',
- 'bird' => '小鸟',
- 'fish' => '小鱼',
- 'rabbit' => '小兔',
- 'hamster' => '小仓鼠',
- ];
- $baseName = $nameMap[$petType] ?? '小宠物';
- // 添加随机后缀以避免重名
- $suffix = rand(1000, 9999);
- return $baseName . $suffix;
- }
- }
|