HostnameValidator.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  15. /**
  16. * @author Dmitrii Poddubnyi <dpoddubny@gmail.com>
  17. */
  18. class HostnameValidator extends ConstraintValidator
  19. {
  20. /**
  21. * https://tools.ietf.org/html/rfc2606.
  22. */
  23. private const RESERVED_TLDS = [
  24. 'example',
  25. 'invalid',
  26. 'localhost',
  27. 'test',
  28. ];
  29. public function validate($value, Constraint $constraint)
  30. {
  31. if (!$constraint instanceof Hostname) {
  32. throw new UnexpectedTypeException($constraint, Hostname::class);
  33. }
  34. if (null === $value || '' === $value) {
  35. return;
  36. }
  37. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  38. throw new UnexpectedValueException($value, 'string');
  39. }
  40. $value = (string) $value;
  41. if ('' === $value) {
  42. return;
  43. }
  44. if (!$this->isValid($value) || ($constraint->requireTld && !$this->hasValidTld($value))) {
  45. $this->context->buildViolation($constraint->message)
  46. ->setParameter('{{ value }}', $this->formatValue($value))
  47. ->setCode(Hostname::INVALID_HOSTNAME_ERROR)
  48. ->addViolation();
  49. }
  50. }
  51. private function isValid(string $domain): bool
  52. {
  53. return false !== filter_var($domain, \FILTER_VALIDATE_DOMAIN, \FILTER_FLAG_HOSTNAME);
  54. }
  55. private function hasValidTld(string $domain): bool
  56. {
  57. return false !== strpos($domain, '.') && !\in_array(substr($domain, strrpos($domain, '.') + 1), self::RESERVED_TLDS, true);
  58. }
  59. }