Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. UrlValidator.php

function UrlValidator::validate

Overrides ConstraintValidatorInterface::validate

File

vendor/symfony/validator/Constraints/UrlValidator.php, line 48

Class

UrlValidator
@author Bernhard Schussek <bschussek@gmail.com>

Namespace

Symfony\Component\Validator\Constraints

Code

public function validate(mixed $value, Constraint $constraint) : void {
    if (!$constraint instanceof Url) {
        throw new UnexpectedTypeException($constraint, Url::class);
    }
    if (null === $value || '' === $value) {
        return;
    }
    if (!\is_scalar($value) && !$value instanceof \Stringable) {
        throw new UnexpectedValueException($value, 'string');
    }
    $value = (string) $value;
    if ('' === $value) {
        return;
    }
    if (null !== $constraint->normalizer) {
        $value = ($constraint->normalizer)($value);
    }
    $pattern = $constraint->relativeProtocol ? str_replace('(%s):', '(?:(%s):)?', static::PATTERN) : static::PATTERN;
    $pattern = \sprintf($pattern, implode('|', $constraint->protocols));
    if (!preg_match($pattern, $value)) {
        $this->context
            ->buildViolation($constraint->message)
            ->setParameter('{{ value }}', $this->formatValue($value))
            ->setCode(Url::INVALID_URL_ERROR)
            ->addViolation();
        return;
    }
    if ($constraint->requireTld) {
        $urlHost = parse_url($value, \PHP_URL_HOST);
        // the host of URLs with a TLD must include at least a '.' (but it can't be an IP address like '127.0.0.1')
        if (!str_contains($urlHost, '.') || filter_var($urlHost, \FILTER_VALIDATE_IP)) {
            $this->context
                ->buildViolation($constraint->tldMessage)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Url::MISSING_TLD_ERROR)
                ->addViolation();
        }
    }
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal