Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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 <colinodell@gmail.com>
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
    public function __construct(FrontMatterDataParserInterface $frontMatterParser)
28
    {
29
        $this->frontMatterParser = $frontMatterParser;
30
    }
31
 
32
    public function parse(string $markdownContent): MarkdownInputWithFrontMatter
33
    {
34
        $cursor = new Cursor($markdownContent);
35
 
36
        // Locate the front matter
37
        $frontMatter = $cursor->match(self::REGEX_FRONT_MATTER);
38
        if ($frontMatter === null) {
39
            return new MarkdownInputWithFrontMatter($markdownContent);
40
        }
41
 
42
        // Trim the last line (ending ---s and newline)
43
        $frontMatter = \preg_replace('/---\R$/', '', $frontMatter);
44
        if ($frontMatter === null) {
45
            return new MarkdownInputWithFrontMatter($markdownContent);
46
        }
47
 
48
        // Parse the resulting YAML data
49
        $data = $this->frontMatterParser->parse($frontMatter);
50
 
51
        // Advance through any remaining newlines which separated the front matter from the Markdown text
52
        $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
        $lineOffset = \preg_match_all('/\R/', $frontMatter . $trailingNewlines) + 1;
57
 
58
        return new MarkdownInputWithFrontMatter($cursor->getRemainder(), $lineOffset, $data);
59
    }
60
}