UpHandler.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 UCore\Helper\Logger;
  10. use Uraus\Kku\Request\RequestLandUp;
  11. use Uraus\Kku\Response\ResponseLandUp;
  12. use UCore\Exception\LogicException;
  13. /**
  14. * 处理土地升级请求
  15. */
  16. class UpHandler extends BaseHandler
  17. {
  18. /**
  19. * 是否需要登录
  20. *
  21. * @var bool
  22. */
  23. protected bool $need_login = true;
  24. /**
  25. * 处理土地升级请求
  26. *
  27. * @param RequestLandUp $data 土地升级请求数据
  28. * @return ResponseLandUp 土地升级响应
  29. */
  30. public function handle(Message $data): Message
  31. {
  32. // 创建响应对象
  33. $response = new ResponseLandUp();
  34. // 获取请求参数
  35. $landId = $data->getLandId();
  36. $userId = $this->user_id;
  37. // 先进行验证,避免不必要的事务开销
  38. $validation = new LandUpgradeValidation([
  39. 'user_id' => $userId,
  40. 'land_id' => $landId
  41. ]);
  42. // 验证数据
  43. $validation->validated();
  44. // 从验证结果中获取升级配置和土地信息
  45. $upgradeConfig = $validation->upgrade_config;
  46. $land = $validation->land;
  47. $targetType = $upgradeConfig->to_type_id;
  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. Logger::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. }