DocParser::incorporateLine()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 19
cts 19
cp 1
rs 9.344
c 0
b 0
f 0
nc 4
cc 4
nop 1
crap 4
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9
 *  - (c) John MacFarlane
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace League\CommonMark;
16
17
use League\CommonMark\Block\Element\AbstractBlock;
18
use League\CommonMark\Block\Element\AbstractStringContainerBlock;
19
use League\CommonMark\Block\Element\Document;
20
use League\CommonMark\Block\Element\Paragraph;
21
use League\CommonMark\Block\Element\StringContainerInterface;
22
use League\CommonMark\Event\DocumentParsedEvent;
23
24
final class DocParser implements DocParserInterface
25
{
26
    /**
27
     * @var EnvironmentInterface
28
     */
29
    private $environment;
30
31
    /**
32
     * @var InlineParserEngine
33
     */
34
    private $inlineParserEngine;
35
36
    /**
37
     * @var int|float
38
     */
39
    private $maxNestingLevel;
40
41
    /**
42
     * @param EnvironmentInterface $environment
43
     */
44 2073
    public function __construct(EnvironmentInterface $environment)
45
    {
46 2073
        $this->environment = $environment;
47 2073
        $this->inlineParserEngine = new InlineParserEngine($environment);
48 2073
        $this->maxNestingLevel = $environment->getConfig('max_nesting_level', \INF);
49 2073
    }
50
51
    /**
52
     * @param string $input
53
     *
54
     * @return string[]
55
     */
56 2064
    private function preProcessInput(string $input): array
57
    {
58 2064
        $lines = \preg_split('/\r\n|\n|\r/', $input);
59
60
        // Remove any newline which appears at the very end of the string.
61
        // We've already split the document by newlines, so we can simply drop
62
        // any empty element which appears on the end.
63 2064
        if (\end($lines) === '') {
64 2013
            \array_pop($lines);
65
        }
66
67 2064
        return $lines;
68
    }
69
70
    /**
71
     * @param string $input
72
     *
73
     * @return Document
74
     */
75 2064
    public function parse(string $input): Document
76
    {
77 2064
        $document = new Document();
78 2064
        $context = new Context($document, $this->environment);
79
80 2064
        $lines = $this->preProcessInput($input);
81 2064
        foreach ($lines as $line) {
82 2064
            $context->setNextLine($line);
83 2064
            $this->incorporateLine($context);
84
        }
85
86 2064
        $lineCount = \count($lines);
87 2064
        while ($tip = $context->getTip()) {
88 2064
            $tip->finalize($context, $lineCount);
89
        }
90
91 2064
        $this->processInlines($context);
92
93 2064
        $this->environment->dispatch(new DocumentParsedEvent($document));
94
95 2064
        return $document;
96
    }
97
98 2064
    private function incorporateLine(ContextInterface $context)
99
    {
100 2064
        $context->getBlockCloser()->resetTip();
101 2064
        $context->setBlocksParsed(false);
102
103 2064
        $cursor = new Cursor($context->getLine());
104
105 2064
        $this->resetContainer($context, $cursor);
106 2064
        $context->getBlockCloser()->setLastMatchedContainer($context->getContainer());
107
108 2064
        $this->parseBlocks($context, $cursor);
109
110
        // What remains at the offset is a text line.  Add the text to the appropriate container.
111
        // First check for a lazy paragraph continuation:
112 2064
        if ($this->handleLazyParagraphContinuation($context, $cursor)) {
113 36
            return;
114
        }
115
116
        // not a lazy continuation
117
        // finalize any blocks not matched
118 2064
        $context->getBlockCloser()->closeUnmatchedBlocks();
119
120
        // Determine whether the last line is blank, updating parents as needed
121 2064
        $this->setAndPropagateLastLineBlank($context, $cursor);
122
123
        // Handle any remaining cursor contents
124 2064
        if ($context->getContainer() instanceof StringContainerInterface) {
125 753
            $context->getContainer()->handleRemainingContents($context, $cursor);
126 1815
        } elseif (!$cursor->isBlank()) {
127
            // Create paragraph container for line
128 1734
            $p = new Paragraph();
129 1734
            $context->addBlock($p);
130 1734
            $cursor->advanceToNextNonSpaceOrTab();
131 1734
            $p->addLine($cursor->getRemainder());
132
        }
133 2064
    }
134
135 2064
    private function processInlines(ContextInterface $context)
136
    {
137 2064
        $walker = $context->getDocument()->walker();
138
139 2064
        while ($event = $walker->next()) {
140 2064
            if (!$event->isEntering()) {
141 2064
                continue;
142
            }
143
144 2064
            $node = $event->getNode();
145 2064
            if ($node instanceof AbstractStringContainerBlock) {
146 2022
                $this->inlineParserEngine->parse($node, $context->getDocument()->getReferenceMap());
147
            }
148
        }
149 2064
    }
150
151
    /**
152
     * Sets the container to the last open child (or its parent)
153
     *
154
     * @param ContextInterface $context
155
     * @param Cursor           $cursor
156
     */
157 2064
    private function resetContainer(ContextInterface $context, Cursor $cursor)
158
    {
159 2064
        $container = $context->getDocument();
160
161 2064
        while ($lastChild = $container->lastChild()) {
162 1119
            if (!($lastChild instanceof AbstractBlock)) {
163
                break;
164
            }
165
166 1119
            if (!$lastChild->isOpen()) {
167 453
                break;
168
            }
169
170 1110
            $container = $lastChild;
171 1110
            if (!$container->matchesNextLine($cursor)) {
172 708
                $container = $container->parent(); // back up to the last matching block
173 708
                break;
174
            }
175
        }
176
177 2064
        $context->setContainer($container);
178 2064
    }
179
180
    /**
181
     * Parse blocks
182
     *
183
     * @param ContextInterface $context
184
     * @param Cursor           $cursor
185
     */
186 2064
    private function parseBlocks(ContextInterface $context, Cursor $cursor)
187
    {
188 2064
        while (!$context->getContainer()->isCode() && !$context->getBlocksParsed()) {
189 2064
            $parsed = false;
190 2064
            foreach ($this->environment->getBlockParsers() as $parser) {
191 2064
                if ($parser->parse($context, $cursor)) {
192 819
                    $parsed = true;
193 1234
                    break;
194
                }
195
            }
196
197 2064
            if (!$parsed || $context->getContainer() instanceof StringContainerInterface || (($tip = $context->getTip()) && $tip->getDepth() >= $this->maxNestingLevel)) {
198 2037
                $context->setBlocksParsed(true);
199 2037
                break;
200
            }
201
        }
202 2064
    }
203
204
    /**
205
     * @param ContextInterface $context
206
     * @param Cursor           $cursor
207
     *
208
     * @return bool
209
     */
210 2064
    private function handleLazyParagraphContinuation(ContextInterface $context, Cursor $cursor): bool
211
    {
212 2064
        $tip = $context->getTip();
213
214 2064
        if ($tip instanceof Paragraph &&
215 2064
            !$context->getBlockCloser()->areAllClosed() &&
216 2064
            !$cursor->isBlank() &&
217 2064
            \count($tip->getStrings()) > 0) {
218
219
            // lazy paragraph continuation
220 36
            $tip->addLine($cursor->getRemainder());
221
222 36
            return true;
223
        }
224
225 2064
        return false;
226
    }
227
228
    /**
229
     * @param ContextInterface $context
230
     * @param Cursor           $cursor
231
     */
232 2064
    private function setAndPropagateLastLineBlank(ContextInterface $context, Cursor $cursor)
233
    {
234 2064
        $container = $context->getContainer();
235
236 2064
        if ($cursor->isBlank() && $lastChild = $container->lastChild()) {
237 468
            if ($lastChild instanceof AbstractBlock) {
238 468
                $lastChild->setLastLineBlank(true);
239
            }
240
        }
241
242 2064
        $lastLineBlank = $container->shouldLastLineBeBlank($cursor, $context->getLineNumber());
243
244
        // Propagate lastLineBlank up through parents:
245 2064
        while ($container instanceof AbstractBlock) {
246 2064
            $container->setLastLineBlank($lastLineBlank);
247 2064
            $container = $container->parent();
248
        }
249 2064
    }
250
}
251