You are here

function lazyloader_preprocess_image in Image Lazyloader 8

Implements hook_preprocess_image().

File

./lazyloader.module, line 51
Lazyloader Module.

Code

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

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

  // Add noscript as a fallback.
  $vars['old_attributes'] = new Attribute($vars['attributes']);

  // Add support for responsive images.
  // @todo Ensure that this logic is enough.
  if (!empty($vars['attributes']['srcset'])) {
    $responsive_image = ResponsiveImage::parse($vars['attributes']['srcset']);
    $uri = $responsive_image
      ->get(0)->uri;
  }
  else {
    $uri = $vars['uri'];
  }
  unset($vars['attributes']['srcset']);
  if ($vars['theme_hook_original'] !== 'lazyloader_image') {

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

  // Set placeholder image.
  if (!isset($image_placeholder_src)) {

    // Path to dummy placeholder image, to be replaced by actual image.
    $image_placeholder = trim($config
      ->get('placeholder'));
    $image_placeholder_src = $image_placeholder ? base_path() . $image_placeholder : 'data:image/gif;base64,R0lGODlhAQABAIAAAP7//wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
  }
  if (isset($vars['attributes']['class']) && is_string($vars['attributes']['class'])) {
    $vars['attributes']['class'] = explode(" ", $vars['attributes']['class']);
  }
  $vars['attributes']['class'][] = 'lazyload';
  $vars['attributes']['src'] = file_create_url($image_placeholder_src);
  if (isset($responsive_image)) {
    $vars['attributes']['data-srcset'] = $responsive_image
      ->__toString();
  }
  else {
    $vars['attributes']['data-src'] = file_create_url($uri);
  }
}