| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?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 App\Module\GameItems\Logics\Item;
- 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\RequestLandFertilizer;
- use Uraus\Kku\Response\ResponseLandFertilizer;
- use UCore\Exception\LogicException;
- /**
- * 处理施肥操作请求
- */
- class FertilizerHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- *
- * @var bool
- */
- protected bool $need_login = true;
- /**
- * 处理施肥操作请求
- *
- * @param RequestLandFertilizer $data 施肥操作请求数据
- * @return ResponseLandFertilizer 施肥操作响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponseLandFertilizer();
- // 获取请求参数
- $landId = $data->getLandId();
- $itemId = $data->getItemId();
- $userId = $this->user_id;
- // 验证土地是否存在且属于当前用户
- // 获取用户所有土地
- $landInfo = LandService::getUserLand($userId,$landId);
- if (!$landInfo) {
- throw new LogicException("土地不存在或不属于当前用户");
- }
- // 验证用户是否拥有该物品
- $hasItem = ItemService::checkItemQuantity($userId, $itemId ,1);
- if ($hasItem->error) {
- throw new LogicException("您没有该肥料物品");
- }
- $crop_growth_time = ItemService::getItemNumericAttribute($itemId,'crop_growth_time',0);
- if ($crop_growth_time <= 0) {
- throw new LogicException("该肥料物品无效");
- }
- DB::beginTransaction();
- try {
- // 调用施肥服务
- $result = CropService::useFertilizer($userId, $landId,$crop_growth_time);
- if ($result->error) {
- throw new LogicException("施肥失败,请检查土地状态或作物生长阶段");
- }
- // 消耗物品
- ItemService::consumeItem($userId, $itemId, null, 1, [
- 'source_type' => 'land_fertilizer',
- 'source_id' => $landId,
- 'details' => [ 'land_id' => $landId ]
- ]);
- Log::info('用户施肥成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'item_id' => $itemId
- ]);
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- throw $e;
- }
- CropService::updateGrowthStage($result->data['crop_id']);
- return $response;
- }
- }
|