WateringHandler.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\Farm\Services\CropService;
  5. use App\Module\Farm\Enums\DISASTER_TYPE;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use UCore\Helper\Logger;
  10. use Uraus\Kku\Request\RequestLandWatering;
  11. use Uraus\Kku\Response\ResponseLandWatering;
  12. use Uraus\Kku\Common\RESPONSE_CODE;
  13. use UCore\Exception\LogicException;
  14. /**
  15. * 处理浇水操作请求
  16. * Watering
  17. *
  18. */
  19. class WateringHandler extends BaseHandler
  20. {
  21. /**
  22. * 是否需要登录
  23. * @var bool
  24. */
  25. protected bool $need_login = true;
  26. /**
  27. * 处理浇水操作请求
  28. *
  29. * @param RequestLandWatering $data 浇水操作请求数据
  30. * @return ResponseLandWatering 浇水操作响应
  31. */
  32. public function handle(Message $data): Message
  33. {
  34. // 创建响应对象
  35. $response = new ResponseLandWatering();
  36. try {
  37. // 获取请求参数
  38. $landId = $data->getLandId();
  39. $userItemId = $data->getItemId();
  40. $userId = $this->user_id;
  41. // 先进行验证,避免不必要的事务开销
  42. $validation = new \App\Module\Farm\Validations\DisasterRemovalValidation([
  43. 'user_id' => $userId,
  44. 'land_id' => $landId,
  45. 'item_id' => $userItemId,
  46. 'disaster_type' => DISASTER_TYPE::DROUGHT->value
  47. ]);
  48. // 验证数据
  49. $validation->validated();
  50. // 验证通过后,开启事务
  51. DB::beginTransaction();
  52. // 执行业务逻辑(不再需要验证)
  53. $result = CropService::removeDisasterWithItem(
  54. $userId,
  55. $landId,
  56. $userItemId,
  57. DISASTER_TYPE::DROUGHT->value,
  58. 'land_watering'
  59. );
  60. // 提交事务
  61. DB::commit();
  62. // 设置响应状态
  63. $this->response->setCode(RESPONSE_CODE::OK);
  64. $this->response->setMsg($result['message']);
  65. } catch (\Exception $e) {
  66. // 系统异常,需要回滚事务
  67. if (DB::transactionLevel() > 0) {
  68. DB::rollBack();
  69. }
  70. Logger::error('浇水操作异常', [
  71. 'user_id' => $this->user_id,
  72. 'land_id' => $landId ?? null,
  73. 'item_id' => $userItemId ?? null,
  74. 'error' => $e->getMessage(),
  75. 'trace' => $e->getTraceAsString()
  76. ]);
  77. // 重新抛出异常,交由框架处理
  78. throw $e;
  79. }
  80. return $response;
  81. }
  82. }