You are here

public function FigureFilter::process in Bootstrap Utilities - Text editor filters 8

Performs the filter processing.

Parameters

string $text: The text string to be filtered.

string $langcode: The language code of the text to be filtered.

Return value

\Drupal\filter\FilterProcessResult The filtered text, wrapped in a FilterProcessResult object, and possibly with associated assets, cacheability metadata and placeholders.

Overrides FilterInterface::process

See also

\Drupal\filter\FilterProcessResult

File

src/Plugin/Filter/FigureFilter.php, line 24

Class

FigureFilter
Add Bootstrap class to any figure.

Namespace

Drupal\bootstrap_utilities\Plugin\Filter

Code

public function process($text, $langcode) {
  $result = new FilterProcessResult($text);
  if (stristr($text, 'figure') !== FALSE) {
    $fig_setting_classes = [];
    $cap_setting_classes = [];
    $fig_setting_classes[] = 'figure';
    $cap_setting_classes[] = 'figure-caption';
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    $figure_elements = $xpath
      ->query('//figure');
    if (!is_null($figure_elements)) {
      foreach ($figure_elements as $element) {
        $existing_classes = [];
        $with_setting_classes = [];
        if ($element
          ->getAttribute('class')) {
          $existing_classes[] = $element
            ->getAttribute('class');
        }
        $with_setting_classes = array_unique(array_merge($existing_classes, $fig_setting_classes), SORT_REGULAR);
        $all_classes = implode(' ', $with_setting_classes);
        $element
          ->setAttribute('class', $all_classes);
      }
    }
    $figcaption_elements = $xpath
      ->query('//figcaption');
    if (!is_null($figcaption_elements)) {
      foreach ($figcaption_elements as $element) {
        $existing_classes = [];
        $with_setting_classes = [];
        if ($element
          ->getAttribute('class')) {
          $existing_classes[] = $element
            ->getAttribute('class');
        }
        $with_setting_classes = array_unique(array_merge($existing_classes, $cap_setting_classes), SORT_REGULAR);
        $all_classes = implode(' ', $with_setting_classes);
        $element
          ->setAttribute('class', $all_classes);
      }
    }
    $result
      ->setProcessedText(Html::serialize($dom));
  }
  return $result;
}