You are here

public function BlazyManager::preRenderImage in Blazy 8

Builds the Blazy image as a structured array ready for ::renderer().

Parameters

array $element: The pre-rendered element.

Return value

array The renderable array of pre-rendered element.

File

src/BlazyManager.php, line 269

Class

BlazyManager
Implements a public facing blazy manager.

Namespace

Drupal\blazy

Code

public function preRenderImage(array $element) {
  $build = $element['#build'];
  unset($element['#build']);
  $item = $build['item'];
  $settings = $build['settings'];
  if (empty($settings['uri']) && is_object($item)) {
    $settings['uri'] = ($entity = $item->entity) && empty($item->uri) ? $entity
      ->getFileUri() : $item->uri;
  }

  // Extract field item attributes for the theme function, and unset them
  // from the $item so that the field template does not re-render them.
  $item_attributes = [];
  if ($item && isset($item->_attributes)) {
    $item_attributes = $item->_attributes;
    unset($item->_attributes);
  }

  // Responsive image integration.
  if (!empty($settings['resimage'])) {
    $settings['responsive_image_style_id'] = $settings['resimage']
      ->id();
    $item_attributes['data-b-lazy'] = $settings['one_pixel'];
    $settings['lazy'] = 'responsive';
    $element['#cache']['tags'] = $this
      ->getResponsiveImageCacheTags($settings['resimage']);
  }
  else {
    if (empty($settings['_no_cache'])) {
      $file_tags = isset($settings['file_tags']) ? $settings['file_tags'] : [];
      $settings['cache_tags'] = empty($settings['cache_tags']) ? $file_tags : Cache::mergeTags($settings['cache_tags'], $file_tags);
      $element['#cache']['max-age'] = -1;
      foreach ([
        'contexts',
        'keys',
        'tags',
      ] as $key) {
        if (!empty($settings['cache_' . $key])) {
          $element['#cache'][$key] = $settings['cache_' . $key];
        }
      }
    }
  }
  $element['#item'] = $item;
  $element['#captions'] = empty($build['captions']) ? [] : [
    'inline' => $build['captions'],
  ];
  $element['#item_attributes'] = $item_attributes;
  $element['#settings'] = $settings;
  foreach ([
    'caption',
    'media',
    'wrapper',
  ] as $key) {
    if (!empty($settings[$key . '_attributes'])) {
      $element["#{$key}" . '_attributes'] = $settings[$key . '_attributes'];
    }
  }
  if (!empty($settings['media_switch'])) {
    if ($settings['media_switch'] == 'content' && !empty($settings['content_url'])) {
      $element['#url'] = $settings['content_url'];
    }
    elseif (!empty($settings['lightbox'])) {
      BlazyLightbox::build($element);
    }
  }
  return $element;
}