You are here

public function MediaThumbnailURLFormatter::viewElements in Media thumbnail URL formatter 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides MediaThumbnailFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/MediaThumbnailURLFormatter.php, line 42

Class

MediaThumbnailURLFormatter
Plugin implementation of the 'media_thumbnail' formatter.

Namespace

Drupal\media_thumbnail_url_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $media_items = $this
    ->getEntitiesToView($items, $langcode);

  // Early opt-out if the field is empty.
  if (empty($media_items)) {
    return $elements;
  }
  $image_style_setting = $this
    ->getSetting('image_style');
  $image_style = $this->imageStyleStorage
    ->load($image_style_setting);

  /** @var \Drupal\media\MediaInterface[] $media_items */
  foreach ($media_items as $delta => $media) {
    $thumbnailUri = $media
      ->get('thumbnail')->entity
      ->getFileUri();
    $url = $image_style ? $image_style
      ->buildUrl($thumbnailUri) : file_create_url($thumbnailUri);
    $url = file_url_transform_relative($url);
    $elements[$delta] = [
      '#markup' => $url,
    ];

    // Add cacheability of each item in the field.
    $this->renderer
      ->addCacheableDependency($elements[$delta], $media);
  }

  // Add cacheability of the image style setting.
  if ($image_style) {
    $this->renderer
      ->addCacheableDependency($elements, $image_style);
  }
  return $elements;
}