| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Module\AppGame\Handler\Land;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Farm\Services\CropService;
- use App\Module\Farm\Validations\CropRemoveValidation;
- use App\Module\GameItems\Services\ItemService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Uraus\Kku\Request\RequestLandRemoveCrop;
- use Uraus\Kku\Response\ResponseLandRemoveCrop;
- use UCore\Exception\LogicException;
- /**
- * 处理铲除作物操作请求
- * RemoveCrop
- */
- class RemoveCropHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理铲除作物操作请求
- *
- * @param RequestLandRemoveCrop $data 铲除作物操作请求数据
- * @return ResponseLandRemoveCrop 铲除作物操作响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandRemoveCrop();
- // 获取请求参数
- $landId = $data->getLandId();
- $toolItemId = $data->getItemId() ?? 0; // 铲除工具ID,可选
- $userId = $this->user_id;
- // 先进行验证,避免不必要的事务开销
- $validation = new CropRemoveValidation([
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'tool_item_id' => $toolItemId
- ]);
- // 验证数据
- $validation->validated();
- try {
- // 验证通过后,开启事务
- DB::beginTransaction();
- // 调用铲除作物服务
- $result = CropService::removeCrop($userId, $landId);
- if (!$result) {
- throw new LogicException("铲除作物失败,请检查土地状态");
- }
- // 如果使用了工具,消耗工具
- if ($toolItemId > 0) {
- ItemService::consumeItem($userId, $toolItemId, null, 1, [
- 'source_type' => 'land_remove_crop',
- 'source_id' => $landId,
- 'details' => ['land_id' => $landId]
- ]);
- }
- // 提交事务
- DB::commit();
- Log::info('用户铲除作物成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'tool_item_id' => $toolItemId
- ]);
- } 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,
- 'tool_item_id' => $toolItemId ?? null,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|