PetCreateValidator.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Module\Pet\Validators;
  3. use App\Module\Pet\Models\PetUser;
  4. use UCore\Validator;
  5. use UCore\Validator\ValidationMessage;
  6. /**
  7. * 宠物创建验证器
  8. *
  9. * 用于验证宠物创建参数的合法性
  10. */
  11. class PetCreateValidator extends Validator
  12. {
  13. use ValidationMessage;
  14. /**
  15. * 验证方法
  16. *
  17. * @param mixed $value 宠物名称
  18. * @param array $data 所有数据
  19. * @return bool 验证是否通过
  20. */
  21. public function validate(mixed $value, array $data): bool
  22. {
  23. $name = $value;
  24. $userId = $data['userId'] ?? 0;
  25. // 验证宠物名称
  26. if (empty($name)) {
  27. $this->throwMessage([], '宠物名称不能为空');
  28. return false;
  29. }
  30. if (mb_strlen($name) > 20) {
  31. $this->throwMessage([], '宠物名称不能超过20个字符');
  32. return false;
  33. }
  34. // 检查用户宠物数量限制
  35. $petCount = PetUser::where('user_id', $userId)->count();
  36. $maxPets = config('pet.max_pets_per_user', 3);
  37. if ($petCount >= $maxPets) {
  38. $this->throwMessage(['max' => $maxPets], "已达到最大宠物数量限制: {max}");
  39. return false;
  40. }
  41. return true;
  42. }
  43. }