| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\Farm\Enums\LAND_TYPE;
- use App\Module\Farm\Models\FarmLand;
- use App\Module\Farm\Models\FarmLandType;
- use App\Module\Farm\Models\FarmUser;
- use Illuminate\Support\Facades\Log;
- use UCore\Validator;
- /**
- * 土地升级特殊土地数量限制验证器
- *
- * 验证特殊土地数量是否已达上限
- */
- class LandUpgradeSpecialLimitValidator extends Validator
- {
- /**
- * 验证特殊土地数量限制
- *
- * @param mixed $value 土地ID
- * @param array $data 包含用户ID的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取参数
- $userIdKey = $this->args[0] ?? 'user_id';
- $upgradeConfigKey = $this->args[1] ?? 'upgrade_config';
-
- $userId = $data[$userIdKey] ?? null;
- $upgradeConfig = $this->validation->$upgradeConfigKey ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- if (!$upgradeConfig) {
- $this->addError('升级配置不存在,请先验证升级路径');
- return false;
- }
- try {
- // 获取目标土地类型
- $targetLandType = FarmLandType::find($upgradeConfig->to_type_id);
- if (!$targetLandType) {
- $this->addError('目标土地类型不存在');
- return false;
- }
- // 如果不是特殊土地,直接通过验证
- if (!$targetLandType->is_special) {
- return true;
- }
- // 获取用户农场信息
- $farmUser = FarmUser::where('user_id', $userId)->first();
- if (!$farmUser) {
- $this->addError('用户农场信息不存在');
- return false;
- }
- // 获取用户当前特殊土地数量
- $specialLandCount = FarmLand::where('user_id', $userId)
- ->whereIn('land_type', [
- LAND_TYPE::GOLD->value,
- LAND_TYPE::BLUE->value,
- LAND_TYPE::PURPLE->value
- ])
- ->count();
- // 获取房屋配置
- $houseConfig = $farmUser->houseConfig;
- if (!$houseConfig) {
- $this->addError('房屋配置不存在');
- return false;
- }
- // 检查特殊土地数量限制
- if ($specialLandCount >= $houseConfig->special_land_limit) {
- $this->addError("特殊土地数量已达上限({$houseConfig->special_land_limit}块),当前已有{$specialLandCount}块");
- return false;
- }
- return true;
- } catch (\Exception $e) {
- Log::error('验证特殊土地数量限制时发生错误', [
- 'user_id' => $userId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- $this->addError('验证特殊土地数量限制时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|