trianity / mparser
A generic content parser that supports the devto markdown format
Requires
- php: ^8.4
- league/commonmark: ^2.0|^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.4
- laravel/pint: ^1.0|^2.0
- pestphp/pest: ^4.0|^5.0
- phpstan/phpstan: ^2.2
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Trianity Mparser parses Markdown content with optional front matter and support for built-in Liquid-style tags. Markdown is rendered to HTML with league/commonmark.
Current release: 1.0.0
Requirements
- PHP 8.4 or 8.5
- Composer
Installation
composer require trianity/mparser
Usage
<?php use Trianity\Mparser\Content; use Trianity\Mparser\ContentParser; $raw = <<<'MARKDOWN' --- title: Content Title description: My Description custom: custom --- ## Testing MARKDOWN; $content = new Content($raw); $content->parse(new ContentParser(), true); echo $content->readBodyHtml(); // <h2>Testing</h2> echo $content->frontMatterGet('title'); // Content Title
ContentParser::parse() stores the parsed front matter and Markdown body in the Content object. Pass true as the second argument to also render the body as HTML.
Front matter
Front matter uses a simple YAML-like key: value format between two --- lines. The parsed values can be read and changed with:
$content->frontMatterHas('title'); $content->frontMatterGet('title', 'Default title'); $content->frontMatterSet('title', 'New title'); $content->getAsArray('tags');
After changing the front matter, call updateRaw() to rebuild the raw content.
Built-in tags
The following tags are registered by default:
| Tag | Example | Output |
|---|---|---|
| Video | {% video /videos/test.mp4 %} |
HTML5 video element |
| Audio | {% audio /audio/test.mp3 %} |
HTML5 audio element |
| YouTube | {% youtube Pfkp-lrJTWM %} |
YouTube iframe |
Custom tags
Custom tags implement Trianity\Mparser\CustomTagParser and receive the tag value as a string:
<?php use Trianity\Mparser\ContentParser; use Trianity\Mparser\CustomTagParser; final class CalloutTagParser implements CustomTagParser { public function parse(string $tag_value): string { return '<aside>'.htmlspecialchars($tag_value, ENT_QUOTES, 'UTF-8').'</aside>'; } } $parser = new ContentParser(); $parser->addCustomTagParser('callout', new CalloutTagParser());
The tag can then be used as {% callout Important notice %}.
Tests
Install the development dependencies and run the Pest test suite:
composer install vendor/bin/pest
License
This project is licensed under the MIT License. See LICENSE.