HarvestHandler.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Module\AppGame\Handler\Land;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\Farm\Services\CropService;
  5. use App\Module\Farm\Services\LandService;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Uraus\Kku\Request\RequestLandHarvest;
  10. use Uraus\Kku\Response\ResponseLandHarvest;
  11. use UCore\Exception\LogicException;
  12. /**
  13. * 处理收获操作请求
  14. */
  15. class HarvestHandler extends BaseHandler
  16. {
  17. /**
  18. * 是否需要登录
  19. * @var bool
  20. */
  21. protected bool $need_login = true;
  22. /**
  23. * 处理收获操作请求
  24. *
  25. * @param RequestLandHarvest $data 收获操作请求数据
  26. * @return ResponseLandHarvest 收获操作响应
  27. */
  28. public function handle(Message $data): Message
  29. {
  30. // 创建响应对象
  31. $response = new ResponseLandHarvest();
  32. try {
  33. // 获取请求参数
  34. $landId = $data->getLandId();
  35. $userId = $this->user_id;
  36. // 验证土地是否存在且属于当前用户
  37. // 获取用户所有土地
  38. $userLands = LandService::getUserLands($userId);
  39. $landInfo = null;
  40. // 查找指定ID的土地
  41. foreach ($userLands as $land) {
  42. if ($land->id == $landId) {
  43. $landInfo = $land;
  44. break;
  45. }
  46. }
  47. if (!$landInfo) {
  48. throw new LogicException("土地不存在或不属于当前用户");
  49. }
  50. DB::beginTransaction();
  51. // 调用收获服务
  52. $res = $harvestResult = CropService::harvestCrop($userId, $landId);
  53. if ($res->error) {
  54. throw new LogicException("收获失败,请检查土地状态或作物生长阶段");
  55. }
  56. Log::info('用户收获成功', [
  57. 'user_id' => $userId,
  58. 'land_id' => $landId,
  59. 'harvest_result' => $harvestResult
  60. ]);
  61. DB::commit();
  62. } catch (\Exception $e) {
  63. DB::rollBack();
  64. // 设置错误响应
  65. $this->response->setCode(400);
  66. $this->response->setMsg($e->getMessage());
  67. Log::warning('用户收获失败', [
  68. 'user_id' => $this->user_id,
  69. 'error' => $e->getMessage(),
  70. 'trace' => $e->getTraceAsString()
  71. ]);
  72. }
  73. return $response;
  74. }
  75. }