1
0

Removed caching and some formating

This commit is contained in:
Richard Dern 2024-05-08 21:14:33 +02:00
parent bc254ddc6b
commit 613910dc33

View File

@ -3,13 +3,9 @@
namespace App\Services\Markdown;
use App\Classes\Bundle;
use App\Services\Markdown\Renderers\LinkRenderer;
use DOMDocument;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Cache;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
use League\CommonMark\Extension\DisallowedRawHtml\DisallowedRawHtmlExtension;
use League\CommonMark\Extension\ExternalLink\ExternalLinkExtension;
use League\CommonMark\Extension\Footnote\FootnoteExtension;
@ -48,13 +44,6 @@ public function render(): string
return $this->source;
}
$hash = md5($this->source);
$cacheKey = sprintf('markdown_formatted_%s', $hash);
if (Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
// First, process the source with Blade to handle any dynamic content
$result = Blade::render($this->source);
@ -64,9 +53,6 @@ public function render(): string
// Perform final adjustments like inserting non-breaking spaces
$result = $this->insertNonBreakingSpaces($converted->getContent());
$result = $this->removeEmptyCodeLines($result);
Cache::put($cacheKey, $result, now()->addMonth());
return $result;
}
@ -101,9 +87,6 @@ protected function prepareEnvironment(): Environment
$environment->addExtension($extension);
}
// Use a custom renderer for links
$environment->addRenderer(Link::class, new LinkRenderer($this->bundle));
return $environment;
}
@ -129,39 +112,4 @@ protected function insertNonBreakingSpaces(string $html): string
// Perform the replacements and return the modified HTML
return preg_replace($patterns, $replacements, $html);
}
/**
* For some reason, to date (04-2024), HighlightCodeExtension appends empty
* lines at the end of a code block. We need to get rid of them.
*/
protected function removeEmptyCodeLines(string $html): string
{
$body = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
libxml_use_internal_errors(true);
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHtml($body);
libxml_clear_errors();
$xpath = new \DOMXPath($dom);
$spans = $xpath->query('//pre/code/span[@class="line" and not(node())]');
foreach ($spans as $span) {
if ($span->isSameNode($span->parentNode->lastChild)) {
$span->parentNode->removeChild($span);
}
}
$finalHtml = '';
$bodyTag = $dom->documentElement->getElementsByTagName('body')->item(0);
foreach ($bodyTag->childNodes as $rootLevelTag) {
$finalHtml .= $dom->saveHTML($rootLevelTag);
}
return $finalHtml;
}
}