PetExistsValidator.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. ->where('user_id',$userId)
  27. ->first();
  28. if (!$pet) {
  29. if ($userId > 0) {
  30. $this->addError('宠物不存在或不属于当前用户');
  31. } else {
  32. $this->addError('宠物不存在');
  33. }
  34. return false;
  35. }
  36. return true;
  37. } catch (\Exception $e) {
  38. $this->addError('验证过程发生错误: ' . $e->getMessage());
  39. return false;
  40. }
  41. }
  42. }