| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- namespace App\Module\Pet\Validators;
- use App\Module\Pet\Models\PetUser;
- use UCore\Validator;
- use UCore\Validator\ValidationMessage;
- /**
- * 宠物创建验证器
- *
- * 用于验证宠物创建参数的合法性
- */
- class PetCreateValidator extends Validator
- {
- use ValidationMessage;
-
- /**
- * 验证方法
- *
- * @param mixed $value 宠物名称
- * @param array $data 所有数据
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $name = $value;
- $userId = $data['userId'] ?? 0;
-
- // 验证宠物名称
- if (empty($name)) {
- $this->throwMessage([], '宠物名称不能为空');
- return false;
- }
-
- if (mb_strlen($name) > 20) {
- $this->throwMessage([], '宠物名称不能超过20个字符');
- return false;
- }
-
- // 检查用户宠物数量限制
- $petCount = PetUser::where('user_id', $userId)->count();
- $maxPets = config('pet.max_pets_per_user', 3);
-
- if ($petCount >= $maxPets) {
- $this->throwMessage(['max' => $maxPets], "已达到最大宠物数量限制: {max}");
- return false;
- }
-
- return true;
- }
- }
|