improvements-2.x-dev/src/Plugin/Filter/NofollowExternalLinksFilter.php
src/Plugin/Filter/NofollowExternalLinksFilter.php
<?php
namespace Drupal\improvements\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\filter\Attribute\Filter;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\filter\Plugin\FilterInterface;
#[Filter(
id: 'nofollow_external_links_filter',
title: new TranslatableMarkup('Nofollow external link'),
type: FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
description: new TranslatableMarkup('Add attribute rel=nofollow to external links.'),
weight: 20,
)]
class NofollowExternalLinksFilter extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode): FilterProcessResult {
$result = new FilterProcessResult($text);
if (stripos($text, '<a') !== FALSE) {
$html_dom = Html::load($text);
$links = $html_dom->getElementsByTagName('a');
foreach ($links as $link) {
$link_href = $link->getAttribute('href');
if (UrlHelper::isExternal($link_href)) {
$link->setAttribute('rel', 'nofollow');
}
}
$result->setProcessedText(Html::serialize($html_dom));
}
return $result;
}
}
