| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?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 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 ?: "收获失败,请检查土地状态或作物生长阶段");
- }
- // 提交事务
- DB::commit();
-
- Log::info('用户收获成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'harvest_result' => $harvestResult->data ?? []
- ]);
- }catch (\Exception $e) {
- // 系统异常,需要回滚事务
- if (DB::transactionLevel() > 0) {
- DB::rollBack();
- }
- $this->response->setCode(500);
- $this->response->setMsg('系统错误,请稍后再试');
- Log::error('收获操作异常', [
- 'user_id' => $userId ?? null,
- 'land_id' => $landId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|