link_obfuscation-1.0.0-beta3/src/Service/ObfuscateLinkService.php
src/Service/ObfuscateLinkService.php
<?php
namespace Drupal\link_obfuscation\Service;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Masterminds\HTML5;
/**
* Provides a class which generates a link with route names and parameters.
*/
class ObfuscateLinkService {
/**
* {@inheritdoc}
*/
public static function getObfuscateAttributesForUri(string $uri): array {
try {
$url = Url::fromUri($uri);
}
catch (\Exception $e) {
// Ignore.
}
if (empty($url)) {
try {
$url = Url::fromUserInput($uri);
}
catch (\Exception $e) {
// Ignore.
}
}
if (empty($url)) {
return [];
}
return static::getObfuscateAttributesForUrl($url);
}
/**
* {@inheritdoc}
*/
public static function getObfuscateAttributesForUrl(Url $url): array {
if (!$url->isExternal() && $url->isRouted()) {
$routeName = $url->getRouteName();
$routeParameters = $url->getRouteParameters();
if ($routeName == '<current>') {
$routeName = \Drupal::routeMatch()->getRouteName();
$routeParameters = \Drupal::routeMatch()->getRawParameters()->all();
}
$lang = $url->getOption('language') instanceof ConfigurableLanguage ?
$url->getOption('language')->id() :
\Drupal::languageManager()->getCurrentLanguage()->getId();
$options = [
'query' => $url->getOption('query'),
'language' => $lang,
'absolute' => $url->getOption('absolute'),
];
return [
'data-internal' => 1,
'data-route-name' => $routeName,
'data-route-parameters' => json_encode($routeParameters),
'data-options' => json_encode(array_filter($options)),
];
}
return [
'data-internal' => 0,
'data-encoded-name' => base64_encode($url->toString()),
];
}
/**
* Obfuscate html.
*/
public function obfuscateHtml(string $htmlText) {
$html5 = new HTML5();
$htmlText = str_replace('<a', '<span', $htmlText);
$htmlText = str_replace('</a>', '</span>', $htmlText);
$domDocument = $html5->loadHTML($htmlText);
foreach ($domDocument->getElementsByTagName('span') as $domLink) {
$href = $domLink->getAttribute('href');
if (empty($href)) {
continue;
}
$url = NULL;
try {
$url = Url::fromUserInput($href);
}
catch (\Exception $e) {
// Ignore.
}
if (empty($url)) {
try {
$url = Url::fromUri($href);
}
catch (\Exception $e) {
// Ignore.
}
}
if (empty($url)) {
continue;
}
$obfuscateAttributes = static::getObfuscateAttributesForUrl($url);
foreach ($obfuscateAttributes as $obfuscateAttributeName => $obfuscateAttribute) {
$domLink->setAttribute($obfuscateAttributeName, $obfuscateAttribute);
}
if ($domLink->getAttribute('target')) {
$domLink->setAttribute('data-target', $domLink->getAttribute('target'));
$domLink->removeAttribute('target');
}
$domLink->removeAttribute('rel');
$domLink->removeAttribute('hreflang');
$classes = $domLink->getAttribute('class');
$classes .= ' drupal-masked-element';
$classes = trim($classes);
$domLink->setAttribute('class', $classes);
$domLink->removeAttribute('href');
}
$obfuscatedContent = $domDocument->saveHTML();
return $obfuscatedContent;
}
}
