You are here

public function MediaResponsiveThumbnailFormatter::viewElements in Media Responsive Thumbnail 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 ResponsiveImageFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/MediaResponsiveThumbnailFormatter.php, line 140

Class

MediaResponsiveThumbnailFormatter
Plugin implementation of the 'media_responsive_thumbnail' formatter.

Namespace

Drupal\media_responsive_thumbnail\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;
  }

  // Collect cache tags to be added for each item in the field.
  $responsive_image_style = $this->responsiveImageStyleStorage
    ->load($this
    ->getSetting('responsive_image_style'));
  $image_styles_to_load = [];
  $cache_tags = [];
  if ($responsive_image_style) {
    $cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style
      ->getCacheTags());
    $image_styles_to_load = $responsive_image_style
      ->getImageStyleIds();
  }
  $image_styles = $this->imageStyleStorage
    ->loadMultiple($image_styles_to_load);
  foreach ($image_styles as $image_style) {
    $cache_tags = Cache::mergeTags($cache_tags, $image_style
      ->getCacheTags());
  }

  /** @var \Drupal\media\MediaInterface[] $media_items */
  foreach ($media_items as $delta => $media) {
    $elements[$delta] = [
      '#theme' => 'responsive_image_formatter',
      '#item' => $media
        ->get('thumbnail')
        ->first(),
      '#item_attributes' => [],
      '#responsive_image_style_id' => $this
        ->getSetting('responsive_image_style'),
      '#url' => $this
        ->getMediaThumbnailUrl($media, $items
        ->getEntity()),
    ];

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

  // Add cacheability of the image style setting.
  if ($this
    ->getSetting('image_link') && ($image_style = $this->responsiveImageStyleStorage
    ->load($this
    ->getSetting('responsive_image_style')))) {
    $this->renderer
      ->addCacheableDependency($elements, $image_style);
  }
  return $elements;
}