HarvestHandler.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 UCore\Helper\Logger;
  12. use Uraus\Kku\Common\LastData;
  13. use Uraus\Kku\Request\RequestLandHarvest;
  14. use Uraus\Kku\Response\ResponseLandHarvest;
  15. use UCore\Exception\LogicException;
  16. /**
  17. * 处理收获操作请求
  18. */
  19. class HarvestHandler extends BaseHandler
  20. {
  21. /**
  22. * 是否需要登录
  23. * @var bool
  24. */
  25. protected bool $need_login = true;
  26. /**
  27. * 处理收获操作请求
  28. *
  29. * @param RequestLandHarvest $data 收获操作请求数据
  30. * @return ResponseLandHarvest 收获操作响应
  31. */
  32. public function handle(Message $data): Message
  33. {
  34. // 创建响应对象
  35. $response = new ResponseLandHarvest();
  36. // 获取请求参数
  37. $landId = $data->getLandId();
  38. $userId = $this->user_id;
  39. // 先进行验证,避免不必要的事务开销
  40. $validation = new CropHarvestValidation([
  41. 'user_id' => $userId,
  42. 'land_id' => $landId
  43. ]);
  44. // 验证数据
  45. $validation->validated();
  46. try {
  47. // 验证通过后,开启事务
  48. DB::beginTransaction();
  49. // 调用收获服务
  50. $harvestResult = CropService::harvestCrop($userId, $landId);
  51. if ($harvestResult->error) {
  52. throw new LogicException($harvestResult->message ?: "收获失败,请检查土地状态或作物生长阶段");
  53. }
  54. // 更新用户活动时间
  55. $this->updateUserActivityTime();
  56. // 提交事务
  57. DB::commit();
  58. Log::info('用户收获成功', [
  59. 'user_id' => $userId,
  60. 'land_id' => $landId,
  61. 'harvest_result' => $harvestResult->data ?? []
  62. ]);
  63. }catch (\Exception $e) {
  64. // 系统异常,需要回滚事务
  65. // if (DB::transactionLevel() > 0) {
  66. DB::rollBack();
  67. // }
  68. Logger::error('收获操作异常', [
  69. 'user_id' => $userId ?? null,
  70. 'land_id' => $landId ?? null,
  71. 'error' => $e->getMessage(),
  72. 'trace' => $e->getTraceAsString()
  73. ]);
  74. // 重新抛出异常,交由框架处理
  75. throw $e;
  76. }
  77. return $response;
  78. }
  79. }