LandOwnershipValidator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\Farm\Models\FarmLand;
  4. use UCore\Validator;
  5. /**
  6. * 土地归属验证器
  7. *
  8. * 验证指定的土地是否属于指定的用户
  9. */
  10. class LandOwnershipValidator extends Validator
  11. {
  12. /**
  13. * 验证土地是否属于用户
  14. *
  15. * @param mixed $value 土地ID
  16. * @param array $data 包含用户ID的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $landId = (int)$value;
  22. // 从 args 获取用户ID的键名,默认为 'user_id'
  23. $userIdKey = $this->args[0] ?? 'user_id';
  24. $userId = $data[$userIdKey] ?? null;
  25. if (!$userId) {
  26. $this->addError('用户ID不能为空');
  27. return false;
  28. }
  29. try {
  30. // 查询土地是否存在且属于指定用户
  31. $land = FarmLand::where('id', $landId)
  32. ->where('user_id', $userId)
  33. ->first();
  34. if (!$land) {
  35. $this->addError("土地(ID: {$landId})不存在或不属于当前用户");
  36. return false;
  37. }
  38. // 可选:将土地实例保存到验证对象中,供后续使用
  39. $landFieldKey = $this->args[1] ?? null;
  40. if ($landFieldKey) {
  41. $this->validation->$landFieldKey = $land;
  42. }
  43. return true;
  44. } catch (\Exception $e) {
  45. $this->addError('验证土地归属时发生错误: ' . $e->getMessage());
  46. return false;
  47. }
  48. }
  49. }