1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the league/commonmark package. |
7
|
|
|
* |
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace League\CommonMark\Extension\FrontMatter; |
15
|
|
|
|
16
|
|
|
use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; |
17
|
|
|
use League\CommonMark\Extension\FrontMatter\Input\MarkdownInputWithFrontMatter; |
18
|
|
|
use League\CommonMark\Parser\Cursor; |
19
|
|
|
|
20
|
|
|
final class FrontMatterParser implements FrontMatterParserInterface |
21
|
|
|
{ |
22
|
|
|
/** @psalm-readonly */ |
23
|
|
|
private FrontMatterDataParserInterface $frontMatterParser; |
24
|
|
|
|
25
|
|
|
private const REGEX_FRONT_MATTER = '/^---\\R.*?\\R---\\R/s'; |
26
|
|
|
|
27
|
32 |
|
public function __construct(FrontMatterDataParserInterface $frontMatterParser) |
28
|
|
|
{ |
29
|
32 |
|
$this->frontMatterParser = $frontMatterParser; |
30
|
|
|
} |
31
|
|
|
|
32
|
32 |
|
public function parse(string $markdownContent): MarkdownInputWithFrontMatter |
33
|
|
|
{ |
34
|
32 |
|
$cursor = new Cursor($markdownContent); |
35
|
|
|
|
36
|
|
|
// Locate the front matter |
37
|
32 |
|
$frontMatter = $cursor->match(self::REGEX_FRONT_MATTER); |
38
|
32 |
|
if ($frontMatter === null) { |
39
|
8 |
|
return new MarkdownInputWithFrontMatter($markdownContent); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
// Trim the last line (ending ---s and newline) |
43
|
24 |
|
$frontMatter = \preg_replace('/---\R$/', '', $frontMatter); |
44
|
24 |
|
if ($frontMatter === null) { |
45
|
|
|
return new MarkdownInputWithFrontMatter($markdownContent); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
// Parse the resulting YAML data |
49
|
24 |
|
$data = $this->frontMatterParser->parse($frontMatter); |
50
|
|
|
|
51
|
|
|
// Advance through any remaining newlines which separated the front matter from the Markdown text |
52
|
20 |
|
$trailingNewlines = $cursor->match('/^\R+/'); |
53
|
|
|
|
54
|
|
|
// Calculate how many lines the Markdown is offset from the front matter by counting the number of newlines |
55
|
|
|
// Don't forget to add 1 because we stripped one out when trimming the trailing delims |
56
|
20 |
|
$lineOffset = \preg_match_all('/\R/', $frontMatter . $trailingNewlines) + 1; |
57
|
|
|
|
58
|
20 |
|
return new MarkdownInputWithFrontMatter($cursor->getRemainder(), $lineOffset, $data); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|