Passed
Push — 2.2 ( 5028d6...47b015 )
by Colin
02:21
created

FrontMatterParser::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 27
ccs 11
cts 12
cp 0.9167
rs 9.9
cc 3
nc 3
nop 1
crap 3.0052
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