You are here

public function BlazyFilter::buildImageItem in Blazy 7

Same name and namespace in other branches
  1. 8.2 src/Plugin/Filter/BlazyFilter.php \Drupal\blazy\Plugin\Filter\BlazyFilter::buildImageItem()
1 call to BlazyFilter::buildImageItem()
BlazyFilter::process in src/Plugin/Filter/BlazyFilter.php

File

src/Plugin/Filter/BlazyFilter.php, line 238

Class

BlazyFilter
Provides a filter to lazyload image, or iframe elements.

Namespace

Drupal\blazy\Plugin\Filter

Code

public function buildImageItem(array &$build, &$node) {
  $settings =& $build['settings'];
  $item = new \stdClass();

  // Checks if we have a valid file entity, not hard-coded image URL.
  if ($src = $node
    ->getAttribute('src')) {

    // If starts with 2 slashes, it is always external.
    if (strpos($src, '//') === 0) {

      // We need to query stored SRC, https is enforced.
      $src = 'https:' . $src;
    }
    if ($node->tagName == 'img') {
      $settings['uri'] = $settings['image_url'] = $src;
    }
    elseif ($node->tagName == 'iframe') {

      // Iframe with data: scheme is a serious kidding, strip it earlier.
      $src = drupal_strip_dangerous_protocols($src);
      $settings['input_url'] = $src;
      $settings['uri'] = $settings['image_url'] = $this
        ->getVideoThumbnail($src);
      $settings['scheme'] = $this
        ->getHost($src);

      // @todo integrate with media WYSIWG via BlazyMedia::getMediaData();.
      $settings['embed_url'] = $this
        ->getVideoEmbedUrl($src);
      $settings['autoplay_url'] = $this
        ->getAutoplayUrl($settings['embed_url']);
      $settings['ratio'] = empty($settings['width']) ? '16:9' : 'fluid';
      $settings['type'] = 'video';
    }

    // Attempts to get the correct URI with hard-coded URL if applicable.
    if (!empty($settings['image_url']) && ($uri = Blazy::buildUri($settings['image_url']))) {
      $settings['uri'] = $item->uri = $uri;
    }
  }

  // Responsive image with aspect ratio requires an extra container to work
  // with Align/ Caption images filters.
  $build['media_attributes']['class'][] = 'media-wrapper media-wrapper--blazy';

  // Copy all attributes of the original node to the $item _attributes.
  if ($node->attributes->length) {
    foreach ($node->attributes as $attribute) {
      if ($attribute->nodeName == 'src') {
        continue;
      }

      // Move classes (align-BLAH,etc) to Blazy container, not image so to
      // work with alignments and aspect ratio. Sanitization is performed at
      // BlazyManager::prepareImage() to avoid double escapes.
      if ($attribute->nodeName == 'class') {
        $build['media_attributes']['class'][] = $attribute->nodeValue;
      }
      else {
        $build['item_attributes'][$attribute->nodeName] = $attribute->nodeValue;
      }
    }
    $build['media_attributes']['class'] = array_unique($build['media_attributes']['class']);
  }
  $build['item'] = $item;
}