PesticideHandler.php 2.6 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 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. // 设置错误响应
  66. $this->response->setCode(500);
  67. $this->response->setMsg('系统错误,请稍后再试');
  68. Log::error('除虫操作异常', [
  69. 'user_id' => $this->user_id,
  70. 'land_id' => $landId ?? null,
  71. 'item_id' => $userItemId ?? null,
  72. 'error' => $e->getMessage(),
  73. 'trace' => $e->getTraceAsString()
  74. ]);
  75. }
  76. return $response;
  77. }
  78. }