1<?php
2
3namespace Drupal\link\Plugin\Validation\Constraint;
4
5use Drupal\Component\Utility\UrlHelper;
6use Symfony\Component\Validator\Constraint;
7use Symfony\Component\Validator\ConstraintValidator;
8
9/**
10 * Validates the LinkExternalProtocols constraint.
11 */
12class LinkExternalProtocolsConstraintValidator extends ConstraintValidator {
13
14  /**
15   * {@inheritdoc}
16   */
17  public function validate($value, Constraint $constraint) {
18    if (isset($value)) {
19      try {
20        /** @var \Drupal\Core\Url $url */
21        $url = $value->getUrl();
22      }
23      // If the URL is malformed this constraint cannot check further.
24      catch (\InvalidArgumentException $e) {
25        return;
26      }
27      // Disallow external URLs using untrusted protocols.
28      if ($url->isExternal() && !in_array(parse_url($url->getUri(), PHP_URL_SCHEME), UrlHelper::getAllowedProtocols())) {
29        $this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
30      }
31    }
32  }
33
34}
35