FertilizerHandler.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\CropService;
  5. use App\Module\Farm\Services\LandService;
  6. use App\Module\GameItems\Logics\Item;
  7. use App\Module\GameItems\Services\ItemService;
  8. use Google\Protobuf\Internal\Message;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Uraus\Kku\Request\RequestLandFertilizer;
  12. use Uraus\Kku\Response\ResponseLandFertilizer;
  13. use UCore\Exception\LogicException;
  14. /**
  15. * 处理施肥操作请求
  16. */
  17. class FertilizerHandler extends BaseHandler
  18. {
  19. /**
  20. * 是否需要登录
  21. *
  22. * @var bool
  23. */
  24. protected bool $need_login = true;
  25. /**
  26. * 处理施肥操作请求
  27. *
  28. * @param RequestLandFertilizer $data 施肥操作请求数据
  29. * @return Res 施肥操作响应
  30. */
  31. public function handle(Message $data): Message
  32. {
  33. // 创建响应对象
  34. $response = new ResponseLandFertilizer();
  35. // 获取请求参数
  36. $landId = $data->getLandId();
  37. $itemId = $data->getItemId();
  38. $userId = $this->user_id;
  39. // 验证土地是否存在且属于当前用户
  40. // 获取用户所有土地
  41. $landInfo = LandService::getUserLand($userId,$landId);
  42. if (!$landInfo) {
  43. throw new LogicException("土地不存在或不属于当前用户");
  44. }
  45. // 验证用户是否拥有该物品
  46. $hasItem = ItemService::checkItemQuantity($userId, $itemId ,1);
  47. if ($hasItem->error) {
  48. throw new LogicException("您没有该肥料物品");
  49. }
  50. $crop_growth_time = ItemService::getItemNumericAttribute($itemId,'crop_growth_time',0);
  51. if ($crop_growth_time <= 0) {
  52. throw new LogicException("该肥料物品无效");
  53. }
  54. DB::beginTransaction();
  55. try {
  56. // 调用施肥服务
  57. $result = CropService::useFertilizer($userId, $landId,$crop_growth_time);
  58. if ($result->error) {
  59. throw new LogicException("施肥失败,请检查土地状态或作物生长阶段");
  60. }
  61. // 消耗物品
  62. ItemService::consumeItem($userId, $itemId, null, 1, [
  63. 'source_type' => 'land_fertilizer',
  64. 'source_id' => $landId,
  65. 'details' => [ 'land_id' => $landId ]
  66. ]);
  67. Log::info('用户施肥成功', [
  68. 'user_id' => $userId,
  69. 'land_id' => $landId,
  70. 'item_id' => $itemId
  71. ]);
  72. DB::commit();
  73. } catch (\Exception $e) {
  74. DB::rollBack();
  75. throw $e;
  76. }
  77. CropService::updateGrowthStage($result->data['crop_id']);
  78. return $response;
  79. }
  80. }