FertilizerHandler.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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\Validations\FertilizerValidation;
  6. use App\Module\GameItems\Services\ItemService;
  7. use Google\Protobuf\Internal\Message;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use Uraus\Kku\Request\RequestLandFertilizer;
  11. use Uraus\Kku\Response\ResponseLandFertilizer;
  12. use UCore\Exception\LogicException;
  13. /**
  14. * 处理施肥操作请求
  15. */
  16. class FertilizerHandler extends BaseHandler
  17. {
  18. /**
  19. * 是否需要登录
  20. *
  21. * @var bool
  22. */
  23. protected bool $need_login = true;
  24. /**
  25. * 处理施肥操作请求
  26. *
  27. * @param RequestLandFertilizer $data 施肥操作请求数据
  28. * @return Message 施肥操作响应
  29. */
  30. public function handle(Message $data): Message
  31. {
  32. // 获取请求参数
  33. $landId = $data->getLandId();
  34. $itemId = $data->getItemId();
  35. $userId = $this->user_id;
  36. Log::info('施肥操作开始', [
  37. 'user_id' => $userId,
  38. 'land_id' => $landId,
  39. 'item_id' => $itemId,
  40. ]);
  41. // 使用FertilizerValidation进行数据验证
  42. Log::info('FertilizerHandler: 开始验证', [
  43. 'user_id' => $userId,
  44. 'land_id' => $landId,
  45. 'item_id' => $itemId,
  46. ]);
  47. $validationData = [
  48. 'user_id' => $userId,
  49. 'land_id' => $landId,
  50. 'item_id' => $itemId,
  51. ];
  52. $validation = new FertilizerValidation($validationData);
  53. $validation->validated(); // 这个方法会在验证失败时抛出异常
  54. try {
  55. DB::beginTransaction();
  56. // 从验证结果中获取数据,避免重复查询
  57. $cropGrowthTime = $validation->crop_growth_time;
  58. // 使用肥料(使用已验证的数据)
  59. $result = CropService::useFertilizer($userId, $landId, $cropGrowthTime);
  60. if ($result->error) {
  61. throw new LogicException("施肥失败:" . $result->message);
  62. }
  63. // 消耗物品
  64. ItemService::consumeItem($userId, $itemId, null, 1, [
  65. 'source_type' => 'land_fertilizer',
  66. 'source_id' => $landId,
  67. 'details' => ['land_id' => $landId]
  68. ]);
  69. DB::commit();
  70. Log::info('施肥操作成功', [
  71. 'user_id' => $userId,
  72. 'land_id' => $landId,
  73. 'item_id' => $itemId,
  74. 'crop_growth_time' => $cropGrowthTime,
  75. ]);
  76. // 更新作物生长阶段
  77. CropService::updateGrowthStage($result->data['crop_id']);
  78. } catch (\Exception $e) {
  79. DB::rollBack();
  80. Log::error('施肥操作失败', [
  81. 'user_id' => $userId,
  82. 'land_id' => $landId,
  83. 'item_id' => $itemId,
  84. 'error' => $e->getMessage(),
  85. ]);
  86. throw $e;
  87. }
  88. // 创建响应对象
  89. $response = new ResponseLandFertilizer();
  90. return $response;
  91. }
  92. }