You are here

public function FilterNoFollowList::process in Nofollow List 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/FilterNoFollowList.php, line 25

Class

FilterNoFollowList
Provides a filter to add nofollow to links.

Namespace

Drupal\nofollowlist\Plugin\Filter

Code

public function process($text, $langcode) {
  $list = preg_split('/\\s+/', $this->settings['nofollowlist_hosts']);
  $html_dom = Html::load($text);
  $links = $html_dom
    ->getElementsByTagName('a');
  foreach ($links as $link) {
    $url = parse_url($link
      ->getAttribute('href'));

    // Handle whitelist option.
    if ($this->settings['nofollowlist_option'] == 'white') {

      // If there is a host present and it is not in the list of allowed hosts
      // we add rel="nofollow".
      if (isset($url['host']) && !in_array($url['host'], $list)) {
        $link
          ->setAttribute('rel', 'nofollow');
      }
    }
    elseif ($this->settings['nofollowlist_option'] == 'black') {

      // If there is a host present and it is in the list of disallowed hosts
      // we add rel="nofollow".
      if (isset($url['host']) && in_array($url['host'], $list)) {
        $link
          ->setAttribute('rel', 'nofollow');
      }
    }
  }
  $text = Html::serialize($html_dom);
  return new FilterProcessResult($text);
}