PetExistsValidator.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Module\Pet\Validators;
  3. use App\Module\Pet\Models\PetUser;
  4. use UCore\Validator;
  5. /**
  6. * 宠物存在验证器
  7. *
  8. * 用于验证宠物是否存在
  9. */
  10. class PetExistsValidator extends Validator
  11. {
  12. /**
  13. * 验证方法
  14. *
  15. * @param mixed $value 宠物ID
  16. * @param array $data 所有数据
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $petId = (int)$value;
  22. $userId = $data['user_id'] ?? 0;
  23. try {
  24. // 获取宠物信息
  25. $pet = PetUser::where('id', $petId)
  26. ->when($userId > 0, function($query) use ($userId) {
  27. return $query->where('user_id', $userId);
  28. })
  29. ->first();
  30. if (!$pet) {
  31. if ($userId > 0) {
  32. $this->addError('宠物不存在或不属于当前用户');
  33. } else {
  34. $this->addError('宠物不存在');
  35. }
  36. return false;
  37. }
  38. return true;
  39. } catch (\Exception $e) {
  40. $this->addError('验证过程发生错误: ' . $e->getMessage());
  41. return false;
  42. }
  43. }
  44. }