You are here

public function FilterAlign::process in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/filter/src/Plugin/Filter/FilterAlign.php \Drupal\filter\Plugin\Filter\FilterAlign::process()

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

core/modules/filter/src/Plugin/Filter/FilterAlign.php, line 24

Class

FilterAlign
Provides a filter to align elements.

Namespace

Drupal\filter\Plugin\Filter

Code

public function process($text, $langcode) {
  $result = new FilterProcessResult($text);
  if (stristr($text, 'data-align') !== FALSE) {
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    foreach ($xpath
      ->query('//*[@data-align]') as $node) {

      // Read the data-align attribute's value, then delete it.
      $align = $node
        ->getAttribute('data-align');
      $node
        ->removeAttribute('data-align');

      // If one of the allowed alignments, add the corresponding class.
      if (in_array($align, [
        'left',
        'center',
        'right',
      ])) {
        $classes = $node
          ->getAttribute('class');
        $classes = strlen($classes) > 0 ? explode(' ', $classes) : [];
        $classes[] = 'align-' . $align;
        $node
          ->setAttribute('class', implode(' ', $classes));
      }
    }
    $result
      ->setProcessedText(Html::serialize($dom));
  }
  return $result;
}