You are here

function _autofloat_filter in AutoFloat 8

Same name and namespace in other branches
  1. 7.2 autofloat.module \_autofloat_filter()
  2. 7 autofloat.module \_autofloat_filter()

Wrap images in a selector with odd/even classes automatically.

1 call to _autofloat_filter()
AutoFloat::process in src/Plugin/Filter/AutoFloat.php
Performs the filter processing.

File

./autofloat.module, line 24
Autofloat module: A filter that floats images left and right automatically.

Code

function _autofloat_filter($text) {
  $target = \Drupal::config('autofloat.settings')
    ->get('target');
  $selector = \Drupal::config('autofloat.settings')
    ->get('selector');

  // Divide the variable into two selectors if a comma is found.
  $selector = explode(',', $selector);

  // Make sure both array keys exist.
  if (isset($selector[0]) == FALSE) {
    $selector[0] = 'non-existing-class-value';
  }
  if (isset($selector[1]) == FALSE) {
    $selector[1] = 'non-existing-class-value';
  }
  $rejector = \Drupal::config('autofloat.settings')
    ->get('rejector');

  // Divide the variable into two rejectors if a comma is found.
  $rejector = explode(',', $rejector);

  // Make sure both array keys exist, if not the regex breaks.
  if (isset($rejector[0]) == FALSE) {
    $rejector[0] = 'non-existing-class-value';
  }
  if (isset($rejector[1]) == FALSE) {
    $rejector[1] = 'non-existing-class-value';
  }
  $count = 0;

  // Load string to DOMDocument.
  $doc = Html::load($text);
  $xpath = new DOMXPath($doc);

  // Iterate through the string neglecting elements nested inside those already
  // processed or those to reject.
  foreach ($xpath
    ->query('//' . $target . '[contains(@class, "float") or contains(@class, "' . $selector[0] . '") or contains(@class, "' . $selector[1] . '")][not(ancestor::*[@class="nofloat"] or ancestor::*[@class="' . $rejector[0] . '"] or ancestor::*[@class="' . $rejector[1] . '"])] | //img[not(ancestor-or-self::*[contains(@class, "nofloat")] or ancestor-or-self::*[contains(@class, "' . $rejector[0] . '")] or ancestor-or-self::*[contains(@class, "' . $rejector[1] . '")] or ancestor::' . $target . '[contains(@class, "float") or contains(@class, "' . $selector[0] . '") or contains(@class, "' . $selector[1] . '")])]') as $tag) {

    // Start on the left or right depending on the settings.
    if (\Drupal::config('autofloat.settings')
      ->get('start') == 0) {
      $zebra = $count % 2 ? 'even' : 'odd';
    }
    else {
      $zebra = $count % 2 ? 'odd' : 'even';
    }
    $count++;

    // Add an alternating class value but maintain the existing ones.
    $tag
      ->setAttribute('class', 'autofloat-' . $zebra . ' ' . $tag
      ->getAttribute('class'));
  }

  // Convert a DOM object back to an HTML snippet.
  $subject = Html::serialize($doc);
  return $subject;
}