You are here

public function BlazyFormatterTrait::buildElements in Blazy 8

Build the Blazy elements.

1 call to BlazyFormatterTrait::buildElements()
BlazyFormatterTrait::viewElements in src/Plugin/Field/FieldFormatter/BlazyFormatterTrait.php

File

src/Plugin/Field/FieldFormatter/BlazyFormatterTrait.php, line 64

Class

BlazyFormatterTrait
A Trait common for blazy image and file ER formatters.

Namespace

Drupal\blazy\Plugin\Field\FieldFormatter

Code

public function buildElements(array &$build, $files) {
  $settings = $build['settings'];
  $item_id = $settings['item_id'];
  $is_media = method_exists($this, 'getMediaItem');
  if (!empty($settings['caption'])) {
    $settings['caption_attributes']['class'][] = $item_id . '__caption';
  }
  foreach ($files as $delta => $file) {

    /* @var Drupal\image\Plugin\Field\FieldType\ImageItem $item */
    $item = $file->_referringItem;
    $settings['delta'] = $delta;
    $settings['file_tags'] = $file
      ->getCacheTags();
    $settings['type'] = 'image';
    $settings['uri'] = $file
      ->getFileUri();
    $box['item'] = $item;
    $box['settings'] = $settings;

    // If imported Drupal\blazy\Dejavu\BlazyVideoTrait.
    if ($is_media) {

      /** @var Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item */

      // EntityReferenceItem provides $item->entity Drupal\file\Entity\File.
      if (!empty($this
        ->getImageItem($item))) {
        $box['item'] = $this
          ->getImageItem($item)['item'];
        $box['settings'] = array_merge($settings, $this
          ->getImageItem($item)['settings']);
      }
      $this
        ->getMediaItem($box, $file);
    }

    // Build caption if so configured.
    if (!empty($settings['caption'])) {
      foreach ($settings['caption'] as $caption) {
        $box['captions'][$caption]['content'] = empty($box['item']->{$caption}) ? [] : [
          '#markup' => Xss::filterAdmin($box['item']->{$caption}),
        ];
        $box['captions'][$caption]['tag'] = $caption == 'title' ? 'h2' : 'div';
        if (!isset($box['captions'][$caption]['attributes'])) {
          $class = $caption == 'alt' ? 'description' : $caption;
          $box['captions'][$caption]['attributes'] = new Attribute();
          $box['captions'][$caption]['attributes']
            ->addClass($item_id . '__' . $class);
        }
      }
    }

    // Image with grid, responsive image, lazyLoad, and lightbox supports.
    $build[$delta] = $this->blazyManager
      ->getImage($box);
    unset($box);
  }
}