UpHandler.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Module\AppGame\Handler\Land;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\Farm\Services\LandService;
  5. use App\Module\Farm\Validations\LandUpgradeValidation;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Uraus\Kku\Request\RequestLandUp;
  10. use Uraus\Kku\Response\ResponseLandUp;
  11. use UCore\Exception\LogicException;
  12. /**
  13. * 处理土地升级请求
  14. */
  15. class UpHandler extends BaseHandler
  16. {
  17. /**
  18. * 是否需要登录
  19. *
  20. * @var bool
  21. */
  22. protected bool $need_login = true;
  23. /**
  24. * 处理土地升级请求
  25. *
  26. * @param RequestLandUp $data 土地升级请求数据
  27. * @return ResponseLandUp 土地升级响应
  28. */
  29. public function handle(Message $data): Message
  30. {
  31. // 创建响应对象
  32. $response = new ResponseLandUp();
  33. // 获取请求参数
  34. $landId = $data->getLandId();
  35. $userId = $this->user_id;
  36. // 先进行验证,避免不必要的事务开销
  37. $validation = new LandUpgradeValidation([
  38. 'user_id' => $userId,
  39. 'land_id' => $landId
  40. ]);
  41. // 验证数据
  42. $validation->validated();
  43. // 从验证结果中获取升级配置和土地信息
  44. $upgradeConfig = $validation->upgrade_config;
  45. $land = $validation->land;
  46. $targetType = $upgradeConfig->to_type_id;
  47. dd($validation);
  48. try {
  49. // 验证通过后,开启事务
  50. DB::beginTransaction();
  51. // 执行业务逻辑(不再需要验证)
  52. $result = LandService::upgradeLand($userId, $landId, $targetType);
  53. if (!$result) {
  54. throw new LogicException("升级土地失败");
  55. }
  56. // 提交事务
  57. DB::commit();
  58. // 记录成功日志
  59. Log::info('用户土地升级成功', [
  60. 'user_id' => $userId,
  61. 'land_id' => $landId,
  62. 'old_type' => $land->land_type,
  63. 'new_type' => $targetType
  64. ]);
  65. } catch (\Exception $e) {
  66. // 系统异常,需要回滚事务
  67. if (DB::transactionLevel() > 0) {
  68. DB::rollBack();
  69. }
  70. Log::error('用户土地升级系统异常', [
  71. 'user_id' => $userId,
  72. 'land_id' => $landId ?? null,
  73. 'error' => $e->getMessage(),
  74. 'trace' => $e->getTraceAsString()
  75. ]);
  76. throw new LogicException('系统异常,请稍后重试');
  77. }
  78. return $response;
  79. }
  80. }