LinkExternalProtocolsConstraintValidator.php

Same filename and directory in other branches
  1. 11.x core/modules/link/src/Plugin/Validation/Constraint/LinkExternalProtocolsConstraintValidator.php
  2. 10 core/modules/link/src/Plugin/Validation/Constraint/LinkExternalProtocolsConstraintValidator.php
  3. 9 core/modules/link/src/Plugin/Validation/Constraint/LinkExternalProtocolsConstraintValidator.php
  4. 8.9.x core/modules/link/src/Plugin/Validation/Constraint/LinkExternalProtocolsConstraintValidator.php

Namespace

Drupal\link\Plugin\Validation\Constraint

File

core/modules/link/src/Plugin/Validation/Constraint/LinkExternalProtocolsConstraintValidator.php

View source
<?php

namespace Drupal\link\Plugin\Validation\Constraint;

use Drupal\Component\Utility\UrlHelper;
use Drupal\link\LinkItemInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
 * Validates the LinkExternalProtocols constraint.
 */
class LinkExternalProtocolsConstraintValidator extends ConstraintValidator {
  
  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) : void {
    if (!$value instanceof LinkItemInterface) {
      throw new UnexpectedValueException($value, LinkItemInterface::class);
    }
    if ($value->isEmpty()) {
      return;
    }
    try {
      /** @var \Drupal\Core\Url $url */
      $url = $value->getUrl();
    } catch (\InvalidArgumentException) {
      return;
    }
    // Disallow external URLs using untrusted protocols.
    if ($url->isExternal() && !in_array(parse_url($url->getUri(), PHP_URL_SCHEME), UrlHelper::getAllowedProtocols())) {
      $this->context
        ->buildViolation($constraint->message, [
        '@uri' => $value->uri,
      ])
        ->atPath('uri')
        ->addViolation();
    }
  }

}

Classes

Title Deprecated Summary
LinkExternalProtocolsConstraintValidator Validates the LinkExternalProtocols constraint.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.