| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- <?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\Services\ItemService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- 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();
- try {
- // 获取请求参数
- $landId = $data->getLandId();
- $itemId = $data->getItemId();
- $itemInstanceId = $data->getItemInstanceId();
- $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("土地不存在或不属于当前用户");
- }
- // 在事务开始前检查土地状态
- if ($landInfo->status !== \App\Module\Farm\Enums\LAND_STATUS::IDLE->value) {
- throw new LogicException("土地状态不允许种植");
- }
- // 验证用户是否拥有该种子物品
- $hasItem = ItemService::getUserItems($userId, ['item_id' => $itemId]);
- if ($hasItem->isEmpty()) {
- throw new LogicException("您没有该种子");
- }
- // 开启数据库事务
- 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();
- 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 (LogicException $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;
- }
- }
|