| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?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\CropPlantValidation;
- use App\Module\GameItems\Services\ItemService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Uraus\Kku\Common\LastData;
- use Uraus\Kku\Request\RequestLandSow;
- use Uraus\Kku\Response\ResponseLandSow;
- use UCore\Exception\LogicException;
- /**
- * 种植操作请求处理器
- */
- class SowHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理种植操作请求
- *
- * @param RequestLandSow $data 种植操作请求数据
- * @return ResponseLandSow 种植操作响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandSow();
- // 获取请求参数
- $landId = $data->getLandId();
- $itemId = $data->getItemId();
- $itemInstanceId = $data->getItemInstanceId();
- $userId = $this->user_id;
- // 先进行验证,避免不必要的事务开销
- $validation = new CropPlantValidation([
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'item_id' => $itemId,
- 'item_instance_id' => $itemInstanceId
- ]);
- // 验证数据
- $validation->validated();
- try {
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 调用Farm模块的CropService种植作物
- $plantResult = CropService::plantCrop($userId, $landId, $itemId);
- if (!$plantResult) {
- throw new LogicException("种植失败,请检查土地状态");
- }
- // 获取种植日志ID
- $sowLogId = $plantResult['log_id'] ?? 0;
- // 消耗种子物品
- ItemService::consumeItem($userId, $itemId, $itemInstanceId, 1, [
- 'source_type' => 'land_sow',
- 'source_id' => $landId,
- 'details' => [
- 'land_id' => $landId,
- 'sow_id' => $sowLogId
- ]
- ]);
- // 提交事务
- DB::commit();
- // LastData 由中间件处理
- Log::info('用户种植成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'seed_id' => $itemId,
- 'item_instance_id' => $itemInstanceId,
- 'crop_id' => $plantResult['crop']->id ?? 0,
- 'sow_log_id' => $sowLogId
- ]);
- } 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,
- 'item_id' => $itemId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|