PesticideHandler.php 2.5 KB

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