shelfwood / markdown-frontmatter
Framework-agnostic YAML frontmatter parsing for PHP
Installs: 0
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/shelfwood/markdown-frontmatter
Requires
- php: ^8.2
- symfony/yaml: ^7.0
Requires (Dev)
- pestphp/pest: ^3.0
README
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