69 lines
1.8 KiB
PHP
69 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Document;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class DocumentPreviewService
|
|
{
|
|
/**
|
|
* 将文档的 Markdown 内容转换为 HTML 用于预览
|
|
* 统一用于 Filament 后台内联预览和独立预览页面
|
|
*
|
|
* @param Document $document
|
|
* @return string HTML 内容
|
|
* @throws \Exception
|
|
*/
|
|
public function convertToHtml(Document $document): string
|
|
{
|
|
return $this->convertMarkdownToHtml($document);
|
|
}
|
|
|
|
/**
|
|
* 将 Markdown 转换为 HTML
|
|
*
|
|
* @param Document $document
|
|
* @return string HTML 内容
|
|
* @throws \Exception
|
|
*/
|
|
public function convertMarkdownToHtml(Document $document): string
|
|
{
|
|
$markdownContent = $document->getMarkdownContent();
|
|
|
|
if (empty($markdownContent)) {
|
|
throw new \Exception('Markdown 内容为空');
|
|
}
|
|
|
|
// 获取 Markdown 文件的目录
|
|
$markdownDir = dirname($document->markdown_path);
|
|
|
|
// 修复图片路径:将 ./media/ 替换为 /markdown/{dir}/media/
|
|
$markdownContent = preg_replace_callback(
|
|
'/\(\.\/media\/([^)]+)\)/',
|
|
function ($matches) use ($markdownDir) {
|
|
$filename = $matches[1];
|
|
return '(/markdown/' . $markdownDir . '/media/' . $filename . ')';
|
|
},
|
|
$markdownContent
|
|
);
|
|
|
|
// 使用 MarkdownRenderService 转换为 HTML
|
|
$renderService = app(MarkdownRenderService::class);
|
|
|
|
return $renderService->render($markdownContent);
|
|
}
|
|
|
|
/**
|
|
* 检查文档是否可以预览
|
|
*
|
|
* @param Document $document
|
|
* @return bool
|
|
*/
|
|
public function canPreview(Document $document): bool
|
|
{
|
|
return $document->conversion_status === 'completed'
|
|
&& !empty($document->markdown_path);
|
|
}
|
|
}
|