<?php

namespace AutoAdmin\Bundle\Content\Service;

use Symfony\Component\DomCrawler\Crawler;

class ObfuscatorService
{
    public const OBFUSCATE_CLASS = 'obfuscated-link';

    public static function obfuscate(string $string): string
    {
        if (empty($string)) {
            return $string;
        }

        $strippedString = strip_tags($string);
        if ($strippedString === $string) {
            return $string;
        }

        $crawler = new Crawler();
        $crawler->addHtmlContent($string);

        $crawler->filter('a.' . self::OBFUSCATE_CLASS)->each(function (Crawler $linkNode) {
            $href = $linkNode->attr('href');
            if ($href) {
                $linkNode->getNode(0)->setAttribute('data-href', $href);
                $linkNode->getNode(0)->setAttribute('href', '#');
            }
        });

        return $crawler->filter('body')->html();
    }
}
