|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Support\CommonMark; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Blade; |
| 6 | +use League\CommonMark\Environment\Environment; |
| 7 | +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; |
| 8 | +use League\CommonMark\MarkdownConverter; |
| 9 | +use Torchlight\Commonmark\V2\TorchlightExtension; |
| 10 | + |
| 11 | +class BladeMarkdownPreprocessor |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Process markdown content to render Blade components before markdown parsing. |
| 15 | + * |
| 16 | + * This extracts code blocks first (to prevent them from being processed), |
| 17 | + * renders any Blade components in the remaining content, then restores |
| 18 | + * the code blocks. Code blocks that end up inside HTML elements are |
| 19 | + * pre-converted to HTML to ensure proper syntax highlighting. |
| 20 | + */ |
| 21 | + public static function process(string $markdown, array $data = []): string |
| 22 | + { |
| 23 | + $codeBlocks = []; |
| 24 | + $placeholder = '___CODE_BLOCK_PLACEHOLDER_%d___'; |
| 25 | + |
| 26 | + // Extract fenced code blocks (``` or ~~~) |
| 27 | + $markdown = preg_replace_callback( |
| 28 | + '/^(`{3,}|~{3,})([^\n]*)\n(.*?)\n\1/ms', |
| 29 | + function ($matches) use (&$codeBlocks, $placeholder) { |
| 30 | + $index = count($codeBlocks); |
| 31 | + $codeBlocks[$index] = $matches[0]; |
| 32 | + |
| 33 | + return sprintf($placeholder, $index); |
| 34 | + }, |
| 35 | + $markdown |
| 36 | + ); |
| 37 | + |
| 38 | + // Extract inline code (single backticks) |
| 39 | + $inlineCode = []; |
| 40 | + $inlinePlaceholder = '___INLINE_CODE_PLACEHOLDER_%d___'; |
| 41 | + $markdown = preg_replace_callback( |
| 42 | + '/`[^`]+`/', |
| 43 | + function ($matches) use (&$inlineCode, $inlinePlaceholder) { |
| 44 | + $index = count($inlineCode); |
| 45 | + $inlineCode[$index] = $matches[0]; |
| 46 | + |
| 47 | + return sprintf($inlinePlaceholder, $index); |
| 48 | + }, |
| 49 | + $markdown |
| 50 | + ); |
| 51 | + |
| 52 | + // Check if there are any Blade components to process |
| 53 | + if (static::containsBladeComponents($markdown)) { |
| 54 | + // Render the content as a Blade string |
| 55 | + $markdown = static::renderBladeContent($markdown, $data); |
| 56 | + } |
| 57 | + |
| 58 | + // Restore inline code |
| 59 | + foreach ($inlineCode as $index => $code) { |
| 60 | + $markdown = str_replace(sprintf($inlinePlaceholder, $index), $code, $markdown); |
| 61 | + } |
| 62 | + |
| 63 | + // Restore code blocks - convert to HTML if inside HTML elements |
| 64 | + foreach ($codeBlocks as $index => $block) { |
| 65 | + $placeholderStr = sprintf($placeholder, $index); |
| 66 | + |
| 67 | + // Check if placeholder is inside an HTML element (after Blade rendering) |
| 68 | + if (static::isInsideHtmlElement($markdown, $placeholderStr)) { |
| 69 | + // Convert code block to HTML before restoring |
| 70 | + $block = static::convertCodeBlockToHtml($block); |
| 71 | + } |
| 72 | + |
| 73 | + $markdown = str_replace($placeholderStr, $block, $markdown); |
| 74 | + } |
| 75 | + |
| 76 | + return $markdown; |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * Check if a placeholder is inside an HTML element. |
| 81 | + */ |
| 82 | + protected static function isInsideHtmlElement(string $content, string $placeholder): bool |
| 83 | + { |
| 84 | + $pos = strpos($content, $placeholder); |
| 85 | + if ($pos === false) { |
| 86 | + return false; |
| 87 | + } |
| 88 | + |
| 89 | + // Get content before placeholder and count open/close tags |
| 90 | + $before = substr($content, 0, $pos); |
| 91 | + |
| 92 | + // Simple heuristic: check if there's an unclosed HTML tag before the placeholder |
| 93 | + // Look for patterns like <div...> that aren't closed |
| 94 | + $openTags = preg_match_all('/<(div|span|section|article|aside|p)[^>]*>(?!.*<\/\1>)/i', $before); |
| 95 | + $lastOpenTag = strrpos($before, '<'); |
| 96 | + $lastCloseTag = strrpos($before, '>'); |
| 97 | + |
| 98 | + // If the last < is after the last >, we're likely inside a tag (shouldn't happen with placeholders) |
| 99 | + // More reliable: check if there's an HTML structure pattern before the placeholder |
| 100 | + return (bool) preg_match('/<[a-z][^>]*>\s*$/i', $before); |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Convert a markdown code block to HTML using Torchlight. |
| 105 | + */ |
| 106 | + protected static function convertCodeBlockToHtml(string $codeBlock): string |
| 107 | + { |
| 108 | + try { |
| 109 | + $config = [ |
| 110 | + 'html_input' => 'allow', |
| 111 | + ]; |
| 112 | + |
| 113 | + $environment = new Environment($config); |
| 114 | + $environment->addExtension(new CommonMarkCoreExtension); |
| 115 | + |
| 116 | + if (class_exists(TorchlightExtension::class)) { |
| 117 | + $environment->addExtension(new TorchlightExtension); |
| 118 | + } |
| 119 | + |
| 120 | + $converter = new MarkdownConverter($environment); |
| 121 | + |
| 122 | + return trim($converter->convert($codeBlock)->getContent()); |
| 123 | + } catch (\Throwable $e) { |
| 124 | + report($e); |
| 125 | + |
| 126 | + return $codeBlock; |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Check if the content contains Blade components. |
| 132 | + */ |
| 133 | + protected static function containsBladeComponents(string $content): bool |
| 134 | + { |
| 135 | + // Look for <x-*> component tags or Blade directives/echoes |
| 136 | + return (bool) preg_match('/<x-[\w\-\.:]+|@[\w]+|{{\s*|{!!\s*/', $content); |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * Render Blade content, handling components and directives. |
| 141 | + */ |
| 142 | + protected static function renderBladeContent(string $content, array $data = []): string |
| 143 | + { |
| 144 | + try { |
| 145 | + return Blade::render($content, $data); |
| 146 | + } catch (\Throwable $e) { |
| 147 | + // If Blade rendering fails, return original content |
| 148 | + // This can happen if the content has invalid Blade syntax |
| 149 | + report($e); |
| 150 | + |
| 151 | + return $content; |
| 152 | + } |
| 153 | + } |
| 154 | +} |
0 commit comments