LandUpgradeSpecialLimitValidator.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\Farm\Enums\LAND_TYPE;
  4. use App\Module\Farm\Models\FarmLand;
  5. use App\Module\Farm\Models\FarmLandType;
  6. use App\Module\Farm\Models\FarmUser;
  7. use Illuminate\Support\Facades\Log;
  8. use UCore\Validator;
  9. /**
  10. * 土地升级特殊土地数量限制验证器
  11. *
  12. * 验证特殊土地数量是否已达上限
  13. */
  14. class LandUpgradeSpecialLimitValidator extends Validator
  15. {
  16. /**
  17. * 验证特殊土地数量限制
  18. *
  19. * @param mixed $value 土地ID
  20. * @param array $data 包含用户ID的数组
  21. * @return bool 验证是否通过
  22. */
  23. public function validate(mixed $value, array $data): bool
  24. {
  25. // 从 args 获取参数
  26. $userIdKey = $this->args[0] ?? 'user_id';
  27. $upgradeConfigKey = $this->args[1] ?? 'upgrade_config';
  28. $userId = $data[$userIdKey] ?? null;
  29. $upgradeConfig = $this->validation->$upgradeConfigKey ?? null;
  30. if (!$userId) {
  31. $this->addError('用户ID不能为空');
  32. return false;
  33. }
  34. if (!$upgradeConfig) {
  35. $this->addError('升级配置不存在,请先验证升级路径');
  36. return false;
  37. }
  38. try {
  39. // 获取目标土地类型
  40. $targetLandType = FarmLandType::find($upgradeConfig->to_type_id);
  41. if (!$targetLandType) {
  42. $this->addError('目标土地类型不存在');
  43. return false;
  44. }
  45. // 如果不是特殊土地,直接通过验证
  46. if (!$targetLandType->is_special) {
  47. return true;
  48. }
  49. // 获取用户农场信息
  50. $farmUser = FarmUser::where('user_id', $userId)->first();
  51. if (!$farmUser) {
  52. $this->addError('用户农场信息不存在');
  53. return false;
  54. }
  55. // 获取用户当前特殊土地数量
  56. $specialLandCount = FarmLand::where('user_id', $userId)
  57. ->whereIn('land_type', [
  58. LAND_TYPE::GOLD->value,
  59. LAND_TYPE::BLUE->value,
  60. LAND_TYPE::PURPLE->value
  61. ])
  62. ->count();
  63. // 获取房屋配置
  64. $houseConfig = $farmUser->houseConfig;
  65. if (!$houseConfig) {
  66. $this->addError('房屋配置不存在');
  67. return false;
  68. }
  69. // 检查特殊土地数量限制
  70. if ($specialLandCount >= $houseConfig->special_land_limit) {
  71. $this->addError("特殊土地数量已达上限({$houseConfig->special_land_limit}块),当前已有{$specialLandCount}块");
  72. return false;
  73. }
  74. return true;
  75. } catch (\Exception $e) {
  76. Log::error('验证特殊土地数量限制时发生错误', [
  77. 'user_id' => $userId,
  78. 'error' => $e->getMessage(),
  79. 'trace' => $e->getTraceAsString()
  80. ]);
  81. $this->addError('验证特殊土地数量限制时发生错误: ' . $e->getMessage());
  82. return false;
  83. }
  84. }
  85. }