| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\Farm\Models\FarmLand;
- use UCore\Validator;
- /**
- * 土地归属验证器
- *
- * 验证指定的土地是否属于指定的用户
- */
- class LandOwnershipValidator 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 {
- // 查询土地是否存在且属于指定用户
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- $this->addError("土地(ID: {$landId})不存在或不属于当前用户");
- return false;
- }
- // 可选:将土地实例保存到验证对象中,供后续使用
- $landFieldKey = $this->args[1] ?? null;
- if ($landFieldKey) {
- $this->validation->$landFieldKey = $land;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证土地归属时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|