You are here

function lazyloader_preprocess_responsive_image in Image Lazyloader 8

Implements hook_preprocess_responsive_image().

1 string reference to 'lazyloader_preprocess_responsive_image'
ThemeRegistryAlter::themeRegistryAlter in src/Hooks/ThemeRegistryAlter.php
Alters the theme registry.

File

./lazyloader.module, line 113
Lazyloader Module.

Code

function lazyloader_preprocess_responsive_image(&$vars) {
  if (_lazyloader_alter($vars)) {
    return;
  }

  /** @var \Drupal\lazyloader\ThemePreprocess $preprocess */
  $preprocess = \Drupal::service('lazyloader.preprocess');
  $vars = $preprocess
    ->attachLibrary($vars);
  $vars = $preprocess
    ->addCacheTags($vars);

  /** @var \Drupal\lazyloader\VisibilityChecker $checker */
  $checker = \Drupal::service('lazyloader.visibility_checker');
  if (!$checker
    ->isEnabled()) {
    return;
  }

  /** @var \Drupal\Core\Template\Attribute $image_attributes */
  foreach ($vars['sources'] as $key => $image_attributes) {
    $responsive_image = ResponsiveImage::parse((string) $image_attributes['srcset']);
    $uri = $responsive_image
      ->get(0)->uri;
    if (!$checker
      ->isValidFilename($uri) || !$checker
      ->isValidImageStyle($uri)) {
      continue;
    }
    $image_attributes
      ->addClass('lazyload');
    unset($vars['sources'][$key]['srcset']);
    $vars['sources'][$key]['data-srcset'] = $responsive_image
      ->__toString();
  }
}