You are here

public function OEmbedResolver::fetchOembedHtml in Gutenberg 8.2

Fetch oEmbed HTML from a remote resource.

This is usually the provider URL.

Parameters

string $url: The oEmbed resource.

Return value

\Drupal\Component\Render\MarkupInterface|null The oEmbed HTML.

Overrides OEmbedResolverInterface::fetchOembedHtml

1 call to OEmbedResolver::fetchOembedHtml()
OEmbedResolver::resolveOembed in src/OEmbedResolver.php
Resolve a URL's oEmbed resource.

File

src/OEmbedResolver.php, line 131

Class

OEmbedResolver
Class for resolving oEmbed URLs.

Namespace

Drupal\gutenberg

Code

public function fetchOembedHtml($url) {
  $output = NULL;
  try {
    $request = $this->httpClient
      ->get($url);
    $response = $request
      ->getBody();

    // No network error occurred.
    $output = '';
    if (!empty($response)) {
      $embed = json_decode($response);
      if (!empty($embed->html)) {
        $output = $embed->html;
      }
      elseif ($embed->type === 'link') {
        $render = [
          '#title' => $embed->title,
          '#type' => 'link',
          '#url' => Url::fromUri($embed->url),
        ];
        $output = $this->renderer
          ->renderPlain($render);
      }
      elseif ($embed->type === 'photo') {
        $render = [
          '#type' => 'html_tag',
          '#tag' => 'img',
          '#attributes' => [
            'alt' => $embed->title,
            'src' => $embed->url,
            'title' => $embed->title,
            'class' => [
              'gutenberg-oembed-image',
            ],
            'style' => 'width:100%',
          ],
          '#prefix' => '<a href="' . htmlentities($url, ENT_QUOTES) . '">',
          '#suffix' => '</a>',
          '#gutenberg_embed_photo' => TRUE,
          '#gutenberg_embed_url' => $url,
        ];
        $output = $this->renderer
          ->renderPlain($render);
      }
    }
  } catch (RequestException $e) {
    watchdog_exception('gutenberg_oembed', $e);
  }
  return $output;
}