getGodId(); $itemId = $data->getItemId(); $userId = $this->user_id; // 如果客户端没有指定物品ID,则自动查找 if (!$itemId || $itemId <= 0) { $itemId = $this->findGodItem($userId, $godId); } // 先进行验证,避免不必要的事务开销 $validation = new \App\Module\Farm\Validations\GodActivationValidation([ 'user_id' => $userId, 'god_id' => $godId, 'item_id' => $itemId ]); // 验证数据 $validation->validated(); // 验证通过后,开启事务 DB::beginTransaction(); // 执行业务逻辑(不再需要验证) $result = $this->activateGodBuff($userId, $godId, $itemId); // 提交事务 DB::commit(); // 设置响应状态 $this->response->setCode(RESPONSE_CODE::OK); $this->response->setMsg($result['message']); } catch (\Exception $e) { // 系统异常,需要回滚事务 if (DB::transactionLevel() > 0) { DB::rollBack(); } Log::error('神像激活操作异常', [ 'user_id' => $this->user_id, 'god_id' => $godId ?? null, 'item_id' => $itemId ?? null, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); // 重新抛出异常,交由框架处理 throw $e; } return $response; } /** * 查找用户背包中具有指定神像种类的物品(备用方法) * 当客户端没有指定物品ID时使用此方法自动查找 * * @param int $userId 用户ID * @param int $godId 神像ID * @return int 物品ID * @throws LogicException */ private function findGodItem(int $userId, int $godId): int { // 获取用户所有物品 $userItems = ItemService::getUserItems($userId); foreach ($userItems as $userItem) { // 检查物品是否具有神像时间属性 $godDuration = ItemService::getItemNumericAttribute($userItem->itemId, 'god_duration_seconds'); // 检查物品的神像种类是否匹配 $godType = ItemService::getItemNumericAttribute($userItem->itemId, 'god_type'); if ($godDuration > 0 && $godType === $godId) { return $userItem->itemId; } } throw new LogicException("您没有对应的神像物品"); } /** * 激活神像buff * * @param int $userId 用户ID * @param int $godId 神像ID * @param int $itemId 物品ID * @return array 激活结果 * @throws LogicException */ private function activateGodBuff(int $userId, int $godId, int $itemId): array { // 获取物品的神像时间属性 $godDurationSeconds = ItemService::getItemNumericAttribute($itemId, 'god_duration_seconds'); $durationHours = $godDurationSeconds > 0 ? ceil($godDurationSeconds / 3600) : 24; // 转换为小时,默认24小时 // 消耗神像物品 ItemService::consumeItem($userId, $itemId, null, 1, [ 'source_type' => 'god_activate', 'source_id' => $godId, 'details' => [ 'god_id' => $godId, 'god_name' => BUFF_TYPE::getName($godId), 'duration_seconds' => $godDurationSeconds ] ]); // 激活神像加持 $buff = BuffService::activateBuff($userId, $godId, $durationHours); if (!$buff) { throw new LogicException("神像激活失败"); } // 记录日志 Log::info('用户激活神像成功', [ 'user_id' => $userId, 'god_id' => $godId, 'item_id' => $itemId, 'duration_seconds' => $godDurationSeconds, 'duration_hours' => $durationHours, 'expire_time' => $buff->expire_time ? $buff->expire_time->toDateTimeString() : null ]); return [ 'message' => '神像激活成功', 'buff' => $buff ]; } }