librarianphp / parsed
一个支持 devto markdown 格式的通用内容解析器
1.0.1
2023-05-07 12:45 UTC
Requires
- ext-curl: *
- ext-json: *
- league/commonmark: ^2.0
- minicli/curly: ^0.2.0
- minicli/stencil: ^0.1.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.16
- pestphp/pest: ^2.5
README
基于 devto 帖子格式,具有前缀和 liquid 标签支持的通用内容解析器。Parsed 使用 league/commonmark 作为基础 markdown 解析器。
当前实现的 liquid 标签
- HTML 视频嵌入(mp4):
{% video path_to_video.mp4 %}
- HTML 音频嵌入(mp3):
{% audio path_to_audio.mp3 %}
- Twitter 嵌入:
{% twitter tweet_id %}
- YouTube 视频嵌入:
{% youtube video_id %}
- GitHub 文件(目前不支持 Gists):
{% github full_path_to_repo_file %}
更多即将到来,欢迎贡献。
安装
composer require librarianphp/parsed
使用示例
<?php use Parsed\Content; use Parsed\ContentParser; $content = "---\n"; $content .= "title: Content Title\n"; $content .= "description: My Description\n"; $content .= "custom: custom\n"; $content .= "---\n"; $content .= "## Testing"; $article = new Content($content); $article->parse(new ContentParser(), true); print_r($article);
Parsed\Content Object
(
[raw] => ---
title: Content Title
description: My Description
custom: custom
---
## Testing
[front_matter] => Array
(
[title] => Content Title
[description] => My Description
[custom] => custom
)
[body_markdown] => ## Testing
[body_html] => <h2>Testing</h2>
)
获取前缀
处理前缀有两种方法:frontMatterHas
和 frontMatterGet
$article = new Content($content); $article->parse(new ContentParser(), true); if ($article->frontMatterHas('title')) { return $article->frontMatterGet('title'); }
创建自定义 liquid 标签
Liquid 标签是实现了 CustomTagParserInterface
接口的类。它们需要实现一个名为 parse
的方法,该方法接收从 markdown 文件调用 liquid 标签时提供的字符串。例如,这是 video
liquid 标签解析器类的完整代码
<?php #src/CustomTagParser/VideoTagParser.php namespace Parsed\CustomTagParser; use Parsed\CustomTagParserInterface; class VideoTagParser implements CustomTagParserInterface { public function parse($tag_value, array $params = []) { return "<video controls>" . "<source src=\"$tag_value\" type=\"video/mp4\">" . "Your browser does not support the video tag." . "</video>"; } }
您需要将自定义标签解析器类包含在 ContentParser 中
$parser = new \Parsed\ContentParser(); $parser->addCustomTagParser('video', new VideoTagParser());
注意:内置的标签解析器已在 ContentParser 中注册。这些是:video
、audio
、twitter
、youtube
和 github
。
例如,如果您在 markdown 中有
{% video /videos/test.mp4 %}
它将标签转换为以下代码
<video controls> <source src="/videos/test.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
测试
Parsed 使用 Pest 作为测试框架。要运行测试
./vendor/bin/pest