getResourceUrl example

// 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);
    }
  }

  /** * Handles exceptions that occur during validation. * * @param \Exception $e * The caught exception. * @param string $error_message * (optional) The error message to set as a constraint violation. */

  public function getMetadata(MediaInterface $media$name) {
    $media_url = $this->getSourceFieldValue($media);
    // The URL may be NULL if the source field is empty, in which case just     // return NULL.     if (empty($media_url)) {
      return NULL;
    }

    try {
      $resource_url = $this->urlResolver->getResourceUrl($media_url);
      $resource = $this->resourceFetcher->fetchResource($resource_url);
    }
    catch (ResourceException $e) {
      $this->messenger->addError($e->getMessage());
      return NULL;
    }

    switch ($name) {
      case 'default_name':
        if ($title = $this->getMetadata($media, 'title')) {
          return $title;
        }


  /** * {@inheritdoc} */
  public function getResourceUrl($url$max_width = NULL, $max_height = NULL) {
    $urls = \Drupal::state()->get(static::class[]);

    if (isset($urls[$url])) {
      return $urls[$url];
    }
    return parent::getResourceUrl($url$max_width$max_height);
  }

}
$max_height = $this->getSetting('max_height');

    foreach ($items as $delta => $item) {
      $main_property = $item->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
      $value = $item->{$main_property};

      if (empty($value)) {
        continue;
      }

      try {
        $resource_url = $this->urlResolver->getResourceUrl($value$max_width$max_height);
        $resource = $this->resourceFetcher->fetchResource($resource_url);
      }
      catch (ResourceException $exception) {
        $this->logger->error("Could not retrieve the remote URL (@url).", ['@url' => $value]);
        continue;
      }

      if ($resource->getType() === Resource::TYPE_LINK) {
        $element[$delta] = [
          '#title' => $resource->getTitle(),
          '#type' => 'link',
          


    $constraint = new OEmbedResourceConstraint();

    $context = $this->prophesize(ExecutionContextInterface::class);

    $provider = $this->prophesize(Provider::class);
    $provider->getName()->willReturn('YouTube');

    $url_resolver = $this->prophesize(UrlResolverInterface::class);
    $url_resolver->getProviderByUrl(Argument::any())->willReturn($provider->reveal());
    $url_resolver->getResourceUrl(Argument::any())->shouldBeCalledOnce();

    $validator = new OEmbedResourceConstraintValidator(
      $url_resolver->reveal(),
      $this->prophesize(ResourceFetcher::class)->reveal(),
      $this->container->get('logger.factory')
    );
    $validator->initialize($context->reveal());
    $validator->validate($this->getValue($media)$constraint);
  }

  /** * Wraps a media entity in an anonymous class to mock a field value. * * @param \Drupal\media\Entity\Media $media * The media object. * * @return object * The mock field value to validate. */

  public function testEndpointMatching($url$resource_url) {
    $this->assertSame(
      $resource_url,
      $this->container->get('media.oembed.url_resolver')->getResourceUrl($url)
    );
  }

  /** * Tests that hook_oembed_resource_url_alter() is invoked. * * @depends testEndpointMatching */
  public function testResourceUrlAlterHook() {
    $this->container->get('module_installer')->install(['media_test_oembed']);

    


    // Return a response instead of a render array so that the frame content     // will not have all the blocks and page elements normally rendered by     // Drupal.     $response = new HtmlResponse('', HtmlResponse::HTTP_OK, [
      'Content-Type' => 'text/html; charset=UTF-8',
    ]);
    $response->addCacheableDependency(Url::createFromRequest($request));

    try {
      $resource_url = $this->urlResolver->getResourceUrl($url$max_width$max_height);
      $resource = $this->resourceFetcher->fetchResource($resource_url);

      $placeholder_token = Crypt::randomBytesBase64(55);

      // Render the content in a new render context so that the cacheability       // metadata of the rendered HTML will be captured correctly.       $element = [
        '#theme' => 'media_oembed_iframe',
        '#resource' => $resource,
        // Even though the resource HTML is untrusted, IFrameMarkup::create()         // will create a trusted string. The only reason this is okay is

  public function validateUrl(array &$form, FormStateInterface $form_state) {
    $url = $form_state->getValue('url');
    if ($url) {
      try {
        $resource_url = $this->urlResolver->getResourceUrl($url);
        $this->resourceFetcher->fetchResource($resource_url);
      }
      catch (ResourceException $e) {
        $form_state->setErrorByName('url', $e->getMessage());
      }
    }
  }

  /** * Submit handler for the add button. * * @param array $form * The form render array. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */
Home | Imprint | This part of the site doesn't use cookies.