| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- namespace App\Module\Pet\Validators;
- use App\Module\Pet\Models\PetUser;
- use UCore\Validator;
- /**
- * 宠物存在验证器
- *
- * 用于验证宠物是否存在
- */
- class PetExistsValidator extends Validator
- {
- /**
- * 验证方法
- *
- * @param mixed $value 宠物ID
- * @param array $data 所有数据
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $petId = (int)$value;
- $userId = $data['user_id'] ?? 0;
- try {
- // 获取宠物信息
- $pet = PetUser::where('id', $petId)
- ->when($userId > 0, function($query) use ($userId) {
- return $query->where('user_id', $userId);
- })
- ->first();
- if (!$pet) {
- if ($userId > 0) {
- $this->addError('宠物不存在或不属于当前用户');
- } else {
- $this->addError('宠物不存在');
- }
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证过程发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|