HarvestHandler.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Module\AppGame\Handler\Land;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\AppGame\Proto\LandInfoDto;
  5. use App\Module\Farm\Services\CropService;
  6. use App\Module\Farm\Services\LandService;
  7. use App\Module\Farm\Validations\CropHarvestValidation;
  8. use Google\Protobuf\Internal\Message;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Uraus\Kku\Common\LastData;
  12. use Uraus\Kku\Request\RequestLandHarvest;
  13. use Uraus\Kku\Response\ResponseLandHarvest;
  14. use UCore\Exception\LogicException;
  15. /**
  16. * 处理收获操作请求
  17. */
  18. class HarvestHandler extends BaseHandler
  19. {
  20. /**
  21. * 是否需要登录
  22. * @var bool
  23. */
  24. protected bool $need_login = true;
  25. /**
  26. * 处理收获操作请求
  27. *
  28. * @param RequestLandHarvest $data 收获操作请求数据
  29. * @return ResponseLandHarvest 收获操作响应
  30. */
  31. public function handle(Message $data): Message
  32. {
  33. // 创建响应对象
  34. $response = new ResponseLandHarvest();
  35. // 获取请求参数
  36. $landId = $data->getLandId();
  37. $userId = $this->user_id;
  38. // 先进行验证,避免不必要的事务开销
  39. $validation = new CropHarvestValidation([
  40. 'user_id' => $userId,
  41. 'land_id' => $landId
  42. ]);
  43. // 验证数据
  44. $validation->validated();
  45. try {
  46. // 验证通过后,开启事务
  47. DB::beginTransaction();
  48. // 调用收获服务
  49. $harvestResult = CropService::harvestCrop($userId, $landId);
  50. if ($harvestResult->error) {
  51. throw new LogicException($harvestResult->message ?: "收获失败,请检查土地状态或作物生长阶段");
  52. }
  53. // 提交事务
  54. DB::commit();
  55. Log::info('用户收获成功', [
  56. 'user_id' => $userId,
  57. 'land_id' => $landId,
  58. 'harvest_result' => $harvestResult->data ?? []
  59. ]);
  60. }catch (\Exception $e) {
  61. // 系统异常,需要回滚事务
  62. if (DB::transactionLevel() > 0) {
  63. DB::rollBack();
  64. }
  65. $this->response->setCode(500);
  66. $this->response->setMsg('系统错误,请稍后再试');
  67. Log::error('收获操作异常', [
  68. 'user_id' => $userId ?? null,
  69. 'land_id' => $landId ?? null,
  70. 'error' => $e->getMessage(),
  71. 'trace' => $e->getTraceAsString()
  72. ]);
  73. }
  74. return $response;
  75. }
  76. }