Completed
Push — master ( fbf2a7...00045a )
by Colin
02:48
created

DocParser::setAndPropagateLastLineBlank()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

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