You are here

public function BlazyFilter::buildGrid in Blazy 7

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

File

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

Class

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

Namespace

Drupal\blazy\Plugin\Filter

Code

public function buildGrid(\DOMDocument &$dom, array &$settings, array $elements = [], array $grid_nodes = []) {
  $xpath = new \DOMXPath($dom);
  $query = $settings['style'] = $settings['column'] ? 'column' : 'grid';
  $grid = FALSE;

  // This is weird, variables not working for xpath?
  $node = $query == 'column' ? $xpath
    ->query('//*[@data-column]') : $xpath
    ->query('//*[@data-grid]');
  if ($node->length > 0 && $node
    ->item(0) && $node
    ->item(0)
    ->hasAttribute('data-' . $query)) {
    $grid = $node
      ->item(0)
      ->getAttribute('data-' . $query);
  }
  if ($grid) {

    // Create the parent grid container, and put it before the first.
    $grids = array_map('trim', explode(' ', $grid));
    foreach ([
      'small',
      'medium',
      'large',
    ] as $key => $item) {
      if (isset($grids[$key])) {
        $settings['grid_' . $item] = $grids[$key];
        $settings['grid'] = $grids[$key];
      }
    }
    $build = [
      'items' => $elements,
      'settings' => $settings,
    ];
    $output = $this->manager
      ->build($build);
    $altered_html = drupal_render($output);
    if ($first = $grid_nodes[0]) {

      // Create the parent grid container, and put it before the first.
      $container = $first->parentNode
        ->insertBefore($dom
        ->createElement('div'), $first);
      $updated_nodes = filter_dom_load($altered_html)
        ->getElementsByTagName('body')
        ->item(0)->childNodes;

      // This extra container ensures hook_blazy_build_alter() aint screw up.
      $container
        ->setAttribute('class', 'blazy-wrapper blazy-wrapper--filter');
      foreach ($updated_nodes as $updated_node) {

        // Import the updated from the new DOMDocument into the original
        // one, importing also the child nodes of the updated node.
        $updated_node = $dom
          ->importNode($updated_node, TRUE);
        $container
          ->appendChild($updated_node);
      }

      // Cleanups old nodes already moved into grids.
      foreach ($grid_nodes as $node) {
        if ($node->parentNode) {
          $node->parentNode
            ->removeChild($node);
        }
      }
    }
  }
}