You are here

public function OEmbedResourceConstraintValidator::validate in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraintValidator.php \Drupal\media\Plugin\Validation\Constraint\OEmbedResourceConstraintValidator::validate()

File

core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraintValidator.php, line 76

Class

OEmbedResourceConstraintValidator
Validates oEmbed resource URLs.

Namespace

Drupal\media\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {

  /** @var \Drupal\media\MediaInterface $media */
  $media = $value
    ->getEntity();

  /** @var \Drupal\media\Plugin\media\Source\OEmbedInterface $source */
  $source = $media
    ->getSource();
  if (!$source instanceof OEmbedInterface) {
    throw new \LogicException('Media source must implement ' . OEmbedInterface::class);
  }
  $url = $source
    ->getSourceFieldValue($media);

  // The URL may be NULL if the source field is empty, which is invalid input.
  if (empty($url)) {
    $this->context
      ->addViolation($constraint->invalidResourceMessage);
    return;
  }

  // Ensure that the URL matches a provider.
  try {
    $provider = $this->urlResolver
      ->getProviderByUrl($url);
  } catch (ResourceException $e) {
    $this
      ->handleException($e, $constraint->unknownProviderMessage);
    return;
  } catch (ProviderException $e) {
    $this
      ->handleException($e, $constraint->providerErrorMessage);
    return;
  }

  // Ensure that the provider is allowed.
  if (!in_array($provider
    ->getName(), $source
    ->getProviders(), TRUE)) {
    $this->context
      ->addViolation($constraint->disallowedProviderMessage, [
      '@name' => $provider
        ->getName(),
    ]);
    return;
  }

  // Verify that resource fetching works, because some URLs might match
  // the schemes but don't support oEmbed.
  try {
    $resource_url = $this->urlResolver
      ->getResourceUrl($url);
    $this->resourceFetcher
      ->fetchResource($resource_url);
  } catch (ResourceException $e) {
    $this
      ->handleException($e, $constraint->invalidResourceMessage);
  }
}