Framework-agnostic markdown frontmatter parser
- PHP 100%
| src | ||
| tests | ||
| .gitignore | ||
| composer.json | ||
| composer.lock | ||
| phpunit.xml | ||
| README.md | ||
| SPEC.md | ||
shelfwood/markdown-frontmatter
Framework-agnostic YAML frontmatter parsing for PHP.
Installation
composer require shelfwood/markdown-frontmatter
Requirements
- PHP 8.2+
- symfony/yaml ^7.0
Usage
use Shelfwood\MarkdownFrontmatter\Parser;
$parser = new Parser();
$content = <<<MD
---
title: My Document
tags: [php, yaml]
published: true
---
# Hello World
This is the content.
MD;
$result = $parser->parse($content);
// Access metadata
$title = $result->metadata->get('title'); // 'My Document'
$tags = $result->metadata->getArray('tags'); // ['php', 'yaml']
$published = $result->metadata->getBool('published'); // true
// Access content
$markdown = $result->content; // "# Hello World\n\nThis is the content."
// Check existence
if ($result->hasMetadata() && $result->hasContent()) {
// Both frontmatter and content present
}
API
Parser
$parser = new Parser();
// Parse content (handles null, empty, or valid markdown)
$result = $parser->parse($content);
// Check if parser supports format (always true)
$parser->supports($content);
ParsedMarkdown
// Access as properties
$result->metadata; // ContentMetadata instance
$result->content; // string
// Or use methods
$result->getMetadata();
$result->getContent();
$result->hasMetadata();
$result->hasContent();
// Create instances
ParsedMarkdown::create(['title' => 'Test'], 'content');
ParsedMarkdown::empty();
ContentMetadata
$metadata->get('key'); // mixed, null if missing
$metadata->get('key', 'default'); // mixed with default
$metadata->getString('key'); // string, '' if missing
$metadata->getArray('key'); // array, [] if missing
$metadata->getBool('key'); // bool, false if missing
$metadata->getInt('key'); // int, 0 if missing
$metadata->getFloat('key'); // float, 0.0 if missing
$metadata->has('key'); // bool
$metadata->isEmpty(); // bool
$metadata->count(); // int
$metadata->toArray(); // array
Error Handling
use Shelfwood\MarkdownFrontmatter\Exceptions\ParseException;
try {
$result = $parser->parse($invalidYaml);
} catch (ParseException $e) {
echo $e->getMessage();
}
Edge Cases
| Input | Result |
|---|---|
null |
Empty ParsedMarkdown |
| Empty string | Empty metadata, empty content |
| No frontmatter | Empty metadata, full content |
| Frontmatter only | Parsed metadata, empty content |
| Invalid YAML | Throws ParseException |
| BOM prefix | Automatically stripped |
License
MIT