| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Module\AppGame\Handler\Land;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Farm\Services\CropService;
- use App\Module\Farm\Services\LandService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- 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();
- try {
- // 获取请求参数
- $landId = $data->getLandId();
- $userId = $this->user_id;
- // 验证土地是否存在且属于当前用户
- // 获取用户所有土地
- $userLands = LandService::getUserLands($userId);
- $landInfo = null;
- // 查找指定ID的土地
- foreach ($userLands as $land) {
- if ($land->id == $landId) {
- $landInfo = $land;
- break;
- }
- }
- if (!$landInfo) {
- throw new LogicException("土地不存在或不属于当前用户");
- }
- DB::beginTransaction();
- // 调用收获服务
- $res = $harvestResult = CropService::harvestCrop($userId, $landId);
- if ($res->error) {
- throw new LogicException("收获失败,请检查土地状态或作物生长阶段");
- }
- Log::info('用户收获成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'harvest_result' => $harvestResult
- ]);
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- // 设置错误响应
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('用户收获失败', [
- 'user_id' => $this->user_id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|