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
|
|
|
/** |
23
|
|
|
* @var FrontMatterDataParserInterface |
24
|
|
|
* |
25
|
|
|
* @psalm-readonly |
26
|
|
|
*/ |
27
|
|
|
private $frontMatterParser; |
28
|
|
|
|
29
|
|
|
private const REGEX_FRONT_MATTER = '/^---\\n.*\\n---\n/s'; |
30
|
|
|
|
31
|
21 |
|
public function __construct(FrontMatterDataParserInterface $frontMatterParser) |
32
|
|
|
{ |
33
|
21 |
|
$this->frontMatterParser = $frontMatterParser; |
34
|
21 |
|
} |
35
|
|
|
|
36
|
21 |
|
public function parse(string $markdownContent): MarkdownInputWithFrontMatter |
37
|
|
|
{ |
38
|
21 |
|
$cursor = new Cursor($markdownContent); |
39
|
|
|
|
40
|
|
|
// Locate the front matter |
41
|
21 |
|
$frontMatter = $cursor->match(self::REGEX_FRONT_MATTER); |
42
|
21 |
|
if ($frontMatter === null) { |
43
|
9 |
|
return new MarkdownInputWithFrontMatter($markdownContent); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// Trim the last 4 characters (ending ---s and newline) |
47
|
12 |
|
$frontMatter = \substr($frontMatter, 0, -4); |
48
|
|
|
|
49
|
|
|
// Parse the resulting YAML data |
50
|
12 |
|
$data = $this->frontMatterParser->parse($frontMatter); |
51
|
|
|
|
52
|
|
|
// Advance through any remaining newlines which separated the front matter from the Markdown text |
53
|
9 |
|
$trailingNewlines = $cursor->match('/^\n+/'); |
54
|
|
|
|
55
|
|
|
// Calculate how many lines the Markdown is offset from the front matter by counting the number of newlines |
56
|
|
|
// Don't forget to add 1 because we stripped one out when trimming the trailing delims |
57
|
9 |
|
$lineOffset = \preg_match_all('/\n/', $frontMatter . $trailingNewlines) + 1; |
58
|
|
|
|
59
|
9 |
|
return new MarkdownInputWithFrontMatter($cursor->getRemainder(), $lineOffset, $data); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|