| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace App\Module\AppGame\Handler\Land;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Farm\Services\LandService;
- use App\Module\Farm\Validations\LandUpgradeValidation;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Helper\Logger;
- use Uraus\Kku\Request\RequestLandUp;
- use Uraus\Kku\Response\ResponseLandUp;
- use UCore\Exception\LogicException;
- /**
- * 处理土地升级请求
- */
- class UpHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- *
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理土地升级请求
- *
- * @param RequestLandUp $data 土地升级请求数据
- * @return ResponseLandUp 土地升级响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandUp();
- // 获取请求参数
- $landId = $data->getLandId();
- $userId = $this->user_id;
- // 先进行验证,避免不必要的事务开销
- $validation = new LandUpgradeValidation([
- 'user_id' => $userId,
- 'land_id' => $landId
- ]);
- // 验证数据
- $validation->validated();
- // 从验证结果中获取升级配置和土地信息
- $upgradeConfig = $validation->upgrade_config;
- $land = $validation->land;
- $targetType = $upgradeConfig->to_type_id;
- try {
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 执行业务逻辑(不再需要验证)
- $result = LandService::upgradeLand($userId, $landId, $targetType);
- if (!$result) {
- throw new LogicException("升级土地失败");
- }
- // 提交事务
- DB::commit();
- // 记录成功日志
- Log::info('用户土地升级成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'old_type' => $land->land_type,
- 'new_type' => $targetType
- ]);
- } catch (\Exception $e) {
- // 系统异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- Logger::error('用户土地升级系统异常', [
- 'user_id' => $userId,
- 'land_id' => $landId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- throw new LogicException('系统异常,请稍后重试');
- }
- return $response;
- }
- }
|