Passed
Push — 2.0 ( b7ed7b...934f6b )
by Colin
35:11 queued 31:18
created

InlineParserEngine   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Test Coverage

Coverage 98.31%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 21
eloc 61
c 2
b 0
f 0
dl 0
loc 149
ccs 58
cts 59
cp 0.9831
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A addPlainText() 0 7 3
B matchParsers() 0 44 8
B parse() 0 53 8
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
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Parser;
18
19
use League\CommonMark\Environment\EnvironmentInterface;
20
use League\CommonMark\Node\Block\AbstractBlock;
21
use League\CommonMark\Node\Inline\AdjacentTextMerger;
22
use League\CommonMark\Node\Inline\Text;
23
use League\CommonMark\Parser\Inline\InlineParserInterface;
24
use League\CommonMark\Reference\ReferenceMapInterface;
25
26
/**
27
 * @internal
28
 */
29
final class InlineParserEngine implements InlineParserEngineInterface
30
{
31
    /** @psalm-readonly */
32
    private EnvironmentInterface $environment;
33
34
    /** @psalm-readonly */
35
    private ReferenceMapInterface $referenceMap;
36
37
    /**
38
     * @var array<int, InlineParserInterface|string|bool>
39
     * @psalm-var list<array{0: InlineParserInterface, 1: string, 2: bool}>
40
     * @phpstan-var array<int, array{0: InlineParserInterface, 1: string, 2: bool}>
41
     */
42
    private array $parsers;
43
44 3129
    public function __construct(EnvironmentInterface $environment, ReferenceMapInterface $referenceMap)
45
    {
46 3129
        $this->environment  = $environment;
47 3129
        $this->referenceMap = $referenceMap;
48
49 3129
        foreach ($environment->getInlineParsers() as $parser) {
50
            \assert($parser instanceof InlineParserInterface);
51 3129
            $regex = $parser->getMatchDefinition()->getRegex();
52
53 3129
            $this->parsers[] = [$parser, $regex, \strlen($regex) !== \mb_strlen($regex)];
54
        }
55 3129
    }
56
57 2823
    public function parse(string $contents, AbstractBlock $block): void
58
    {
59 2823
        $contents = \trim($contents);
60 2823
        $cursor   = new Cursor($contents);
61
62 2823
        $inlineParserContext = new InlineParserContext($cursor, $block, $this->referenceMap);
63
64
        // Have all parsers look at the line to determine what they might want to parse and what positions they exist at
65 2823
        foreach ($this->matchParsers($contents) as $matchPosition => $parsers) {
66 2151
            $currentPosition = $cursor->getPosition();
67
            // We've already gone past this point
68 2151
            if ($currentPosition > $matchPosition) {
69 972
                continue;
70
            }
71
72
            // We've skipped over some uninteresting text that should be added as a plain text node
73 2151
            if ($currentPosition < $matchPosition) {
74 1875
                $cursor->advanceBy($matchPosition - $currentPosition);
75 1875
                $this->addPlainText($cursor->getPreviousText(), $block);
76
            }
77
78
            // We're now at a potential start - see which of the current parsers can handle it
79 2151
            $parsed = false;
80 2151
            foreach ($parsers as [$parser, $matches]) {
81
                \assert($parser instanceof InlineParserInterface);
82 2151
                if ($parser->parse($inlineParserContext->withMatches($matches))) {
83
                    // A parser has successfully handled the text at the given position; don't consider any others at this position
84 2139
                    $parsed = true;
85 2139
                    break;
86
                }
87
            }
88
89 2151
            if ($parsed) {
90 2139
                continue;
91
            }
92
93
            // Despite potentially being interested, nothing actually parsed text here, so add the current character and continue onwards
94 177
            $this->addPlainText((string) $cursor->getCurrentCharacter(), $block);
95 177
            $cursor->advance();
96
        }
97
98
        // Add any remaining text that wasn't parsed
99 2823
        if (! $cursor->isAtEnd()) {
100 1479
            $this->addPlainText($cursor->getRemainder(), $block);
101
        }
102
103
        // Process any delimiters that were found
104 2823
        $delimiterStack = $inlineParserContext->getDelimiterStack();
105 2823
        $delimiterStack->processDelimiters(null, $this->environment->getDelimiterProcessors());
106 2823
        $delimiterStack->removeAll();
107
108
        // Combine adjacent text notes into one
109 2823
        AdjacentTextMerger::mergeChildNodes($block);
110 2823
    }
111
112 2622
    private function addPlainText(string $text, AbstractBlock $container): void
113
    {
114 2622
        $lastInline = $container->lastChild();
115 2622
        if ($lastInline instanceof Text && ! $lastInline->data->has('delim')) {
116 270
            $lastInline->append($text);
117
        } else {
118 2586
            $container->appendChild(new Text($text));
119
        }
120 2622
    }
121
122
    /**
123
     * Given the current line, ask all the parsers which parts of the text they would be interested in parsing.
124
     *
125
     * The resulting array provides a list of character positions, which parsers are interested in trying to parse
126
     * the text at those points, and (for convenience/optimization) what the matching text happened to be.
127
     *
128
     * @return array<array<int, InlineParserInterface|string>>
129
     *
130
     * @psalm-return array<int, list<array{0: InlineParserInterface, 1: non-empty-array<string>}>>
131
     *
132
     * @phpstan-return array<int, array<int, array{0: InlineParserInterface, 1: non-empty-array<string>}>>
133
     */
134 2823
    private function matchParsers(string $contents): array
135
    {
136 2823
        $contents    = \trim($contents);
137 2823
        $isMultibyte = \mb_strlen($contents) !== \strlen($contents);
138
139 2823
        $ret = [];
140
141 2823
        foreach ($this->parsers as [$parser, $regex, $isRegexMultibyte]) {
142 2823
            if ($isMultibyte || $isRegexMultibyte) {
143 126
                $regex .= 'u';
144
            }
145
146
            // See if the parser's InlineParserMatch regex matched against any part of the string
147 2823
            if (! \preg_match_all($regex, $contents, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER)) {
148 2817
                continue;
149
            }
150
151
            // For each part that matched...
152 2151
            foreach ($matches as $match) {
153 2151
                if ($isMultibyte) {
154
                    // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying
155 66
                    $offset = \mb_strlen(\substr($contents, 0, $match[0][1]), 'UTF-8');
156
                } else {
157 2085
                    $offset = $match[0][1];
158
                }
159
160
                \assert(\is_int($offset));
161
162
                // Remove the offsets, keeping only the matched text
163 2151
                $m = \array_map(static fn (array $s): string => (string) $s[0], $match);
164
165 2151
                if ($m === []) {
166
                    continue;
167
                }
168
169
                // Add this match to the list of character positions to stop at
170 2151
                $ret[$offset][] = [$parser, $m];
171
            }
172
        }
173
174
        // Sort matches by position so we visit them in order
175 2823
        \ksort($ret);
176
177 2823
        return $ret;
178
    }
179
}
180