| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace App\Module\AppGame\Handler\Land;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\AppGame\Proto\LandInfoDto;
- use App\Module\Farm\Services\CropService;
- use App\Module\Farm\Services\LandService;
- use App\Module\Farm\Validations\CropHarvestValidation;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Helper\Logger;
- use Uraus\Kku\Common\LastData;
- use Uraus\Kku\Request\RequestLandHarvest;
- use Uraus\Kku\Response\ResponseLandHarvest;
- use UCore\Exception\LogicException;
- /**
- * 处理收获操作请求
- */
- class HarvestHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理收获操作请求
- *
- * @param RequestLandHarvest $data 收获操作请求数据
- * @return ResponseLandHarvest 收获操作响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandHarvest();
- // 获取请求参数
- $landId = $data->getLandId();
- $userId = $this->user_id;
- // 先进行验证,避免不必要的事务开销
- $validation = new CropHarvestValidation([
- 'user_id' => $userId,
- 'land_id' => $landId
- ]);
- // 验证数据
- $validation->validated();
- try {
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 调用收获服务
- $harvestResult = CropService::harvestCrop($userId, $landId);
- if ($harvestResult->error) {
- throw new LogicException($harvestResult->message ?: "收获失败,请检查土地状态或作物生长阶段");
- }
- // 更新用户活动时间
- $this->updateUserActivityTime();
- // 提交事务
- DB::commit();
- Log::info('用户收获成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'harvest_result' => $harvestResult->data ?? []
- ]);
- }catch (\Exception $e) {
- // 系统异常,需要回滚事务
- // if (DB::transactionLevel() > 0) {
- DB::rollBack();
- // }
- Logger::error('收获操作异常', [
- 'user_id' => $userId ?? null,
- 'land_id' => $landId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- // 重新抛出异常,交由框架处理
- throw $e;
- }
- return $response;
- }
- }
|