| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\Farm\Models\FarmLand;
- use App\Module\Farm\Services\LandService;
- use UCore\Validator;
- /**
- * 土地升级路径验证器
- *
- * 验证土地是否有可用的升级路径
- */
- class LandUpgradePathValidator extends Validator
- {
- /**
- * 验证土地升级路径
- *
- * @param mixed $value 土地ID
- * @param array $data 包含用户ID的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $landId = (int)$value;
- // 从 args 获取用户ID的键名,默认为 'user_id'
- $userIdKey = $this->args[0] ?? 'user_id';
- $userId = $data[$userIdKey] ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 获取可用的升级路径
- $upgradePaths = LandService::getAvailableUpgradePaths($userId, $landId);
- if (empty($upgradePaths)) {
- $this->addError('当前没有可用的升级路径');
- return false;
- }
- // 选择第一个可用的升级路径
- $upgradePath = $upgradePaths[0];
- // 获取土地信息
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- $this->addError('土地不存在');
- return false;
- }
- // 获取升级配置(只检查配置是否存在,不进行其他验证)
- $upgradeConfig = \App\Module\Farm\Models\FarmLandUpgradeConfig::where('from_type_id', $land->land_type)
- ->where('to_type_id', $upgradePath['to_type_id'])
- ->first();
- if (!$upgradeConfig) {
- $this->addError('升级配置不存在');
- return false;
- }
- // 将升级配置保存到验证对象中,供后续使用
- $upgradeConfigKey = $this->args[1] ?? null;
- if ($upgradeConfigKey) {
- $this->validation->$upgradeConfigKey = $upgradeConfig;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证升级路径时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|