PesticideHandler.php 2.5 KB

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