| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?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)
- ->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;
- }
- }
- }
|