Last active
September 7, 2017 20:33
-
-
Save chx/0c1daa65eb9ba791186f2bac001c120c to your computer and use it in GitHub Desktop.
FilterUrlNormalizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FilterUrlNormalizer extends FilterBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function process($text, $langcode) { | |
$dom = Html::load($text); | |
$metadata = new CacheableMetadata(); | |
/** @var \DOMElement $element */ | |
foreach ($dom->getElementsByTagName('a') as $element) { | |
$link = $element->getAttribute('href'); | |
if (!$link || $link[0] === '#') { | |
continue; | |
} | |
if (($url = \Drupal::pathValidator()->getUrlIfValidWithoutAccessCheck($link)) && $url->isRouted()) { | |
$generated_url = $url->toString(TRUE); | |
$metadata = $metadata->merge($generated_url); | |
$element->setAttribute('href', $generated_url->getGeneratedUrl()); | |
} | |
} | |
$result = new FilterProcessResult(Html::serialize($dom)); | |
return $result->merge($metadata); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment