Текстовый фильтр добавляющий внешним ссылкам атрибут rel=nofollow
15 декабря 2020
<?php
// src/Plugin/Filter/NofollowExternalLinksFilter.php
namespace Drupal\modulename\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* @Filter(
* id = "nofollow_external_links_filter",
* title = @Translation("Nofollow external links"),
* description = @Translation("Add attribute rel=nofollow to external links."),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
* weight = 20,
* )
*/
class NofollowExternalLinksFilter extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode) {
$result = new FilterProcessResult($text);
if (stripos($text, '<a') !== FALSE) {
$html_dom = Html::load($text);
$links = $html_dom->getElementsByTagName('a');
foreach ($links as $link) {
if (UrlHelper::isExternal($link->getAttribute('href'))) {
$link->setAttribute('rel', 'nofollow');
}
}
$result->setProcessedText(Html::serialize($html_dom));
}
return $result;
}
}