fetchResource example

// 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         // because we are serving it in an iframe, which will mitigate the
    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. */
$client = $this->prophesize(Client::class);
    $client->request('GET', $url[RequestOptions::TIMEOUT => 5])
      ->shouldBeCalled()
      ->willReturn($response);

    $fetcher = new ResourceFetcher(
      $client->reveal(),
      $this->createMock('\Drupal\media\OEmbed\ProviderRepositoryInterface'),
      new NullBackend('default')
    );
    $fetcher->fetchResource($url);
  }

  /** * Tests how the resource fetcher handles unknown Content-Type headers. * * @covers ::fetchResource */
  public function testUnknownContentTypeHeader(): void {
    $headers = [
      'Content-Type' => ['text/html'],
    ];
    
    // until we find a match.     foreach ($this->providers->getAll() as $provider_info) {
      foreach ($provider_info->getEndpoints() as $endpoint) {
        if ($endpoint->matchUrl($url)) {
          return $provider_info;
        }
      }
    }

    $resource_url = $this->discoverResourceUrl($url);
    if ($resource_url) {
      return $this->resourceFetcher->fetchResource($resource_url)->getProvider();
    }

    throw new ResourceException('No matching provider found.', $url);
  }

  /** * {@inheritdoc} */
  public function getResourceUrl($url$max_width = NULL, $max_height = NULL) {
    // Try to get the resource URL from the static cache.     if (isset($this->urlCache[$url])) {
      
$url_resolver = $this->prophesize('\Drupal\media\OEmbed\UrlResolverInterface');
    $resource_fetcher = $this->prophesize('\Drupal\media\OEmbed\ResourceFetcherInterface');

    $provider = new Provider('YouTube', 'https://youtube.com', [
      [
        'url' => 'https://youtube.com/foo',
      ],
    ]);
    $resource = Resource::rich('<iframe src="https://youtube.com/watch?feature=oembed"></iframe>', 320, 240, $provider);

    $resource_fetcher->fetchResource(Argument::cetera())->willReturn($resource);

    $this->container->set('media.oembed.url_resolver', $url_resolver->reveal());
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    $request = new Request([
      'url' => '',
      'hash' => $hash,
    ]);
    $response = $this->container->get('html_response.attachments_processor')
      ->processAttachments(OEmbedIframeController::create($this->container)
        ->render($request));
    
$thumbnail_url = $resource->getThumbnailUrl()->toString();

    // There's no need to resolve the resource URL in this test; we just need     // to fetch the resource.     $this->container->set(
      'media.oembed.url_resolver',
      $this->prophesize(UrlResolverInterface::class)->reveal()
    );

    // Mock the resource fetcher so that it will return our fake resource.     $resource_fetcher = $this->prophesize(ResourceFetcherInterface::class);
    $resource_fetcher->fetchResource(Argument::any())
      ->willReturn($resource);
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    // The source plugin will try to fetch the remote thumbnail, so mock the     // HTTP client to ensure that request returns a response with some valid     // image data.     $data = Utils::tryFopen($this->getDrupalRoot() . '/core/misc/druplicon.png', 'r');
    $response = new Response(200, $thumbnail_headers, Utils::streamFor($data));
    $handler = new MockHandler([$response]);
    $client = new Client([
      'handler' => new HandlerStack($handler),
    ]);

  public function testFetchResource($resource_url$provider_name$title) {
    /** @var \Drupal\media\OEmbed\Resource $resource */
    $resource = $this->container->get('media.oembed.resource_fetcher')
      ->fetchResource($resource_url);

    $this->assertInstanceOf(Resource::class$resource);
    $this->assertSame($provider_name$resource->getProvider()->getName());
    $this->assertSame($title$resource->getTitle());
  }

}

  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;
        }
        
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',
          '#url' => Url::fromUri($value),
        ];

  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.