You are here

public function FilterElf::process in External Links Filter 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/FilterElf.php, line 47

Class

FilterElf
Adds a CSS class to all external and mailto links.

Namespace

Drupal\elf\Plugin\Filter

Code

public function process($text, $langcode) {
  $elf_settings = \Drupal::config('elf.settings');
  $result = new FilterProcessResult($text);
  $dom = Html::load($text);
  $links = $dom
    ->getElementsByTagName('a');
  foreach ($links as $a) {
    $href = $a
      ->getAttribute('href');
    if (!$href) {
      continue;
    }

    // This is a mailto link.
    if (strpos($href, 'mailto:') === 0) {
      $a
        ->setAttribute('class', $a
        ->getAttribute('class') ? $a
        ->getAttribute('class') . ' elf-mailto elf-icon' : 'elf-mailto elf-icon');
      continue;
    }

    // This is external links.
    if ($this
      ->elf_url_external($href)) {

      // The link is external. Add external class.
      $a
        ->setAttribute('class', $a
        ->getAttribute('class') ? $a
        ->getAttribute('class') . ' elf-external elf-icon' : 'elf-external elf-icon');
      if ($a
        ->getElementsByTagName('img')->length > 0) {
        $a
          ->setAttribute('class', $a
          ->getAttribute('class') ? $a
          ->getAttribute('class') . ' elf-img' : 'elf-img');
      }

      // Add nofollow.
      $no_follow = $this
        ->getConfiguration()['settings']['elf_nofollow'];
      if ($no_follow) {
        $rel = array_filter(explode(' ', $a
          ->getAttribute('rel')));
        if (!in_array('nofollow', $rel)) {
          $rel[] = 'nofollow';
          $a
            ->setAttribute('rel', implode(' ', $rel));
        }
      }

      // Add redirect.
      if ($elf_settings
        ->get('elf_redirect')) {
        $redirect_url = \Drupal::service('elf.manager')
          ->getRedirectUrl($a
          ->getAttribute('href'));
        $a
          ->setAttribute('href', $redirect_url
          ->toString());
      }
    }
  }
  $result
    ->setProcessedText(Html::serialize($dom))
    ->addAttachments([
    'library' => [
      'elf/elf_css',
    ],
  ]);
  return $result;
}