Completed
Push — master ( d2636b...e88807 )
by Colin
02:51
created

NewlineParser::parse()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 16
cts 16
cp 1
rs 8.5906
cc 5
eloc 14
nc 6
nop 1
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\Inline\Parser;
16
17
use League\CommonMark\Inline\Element\Newline;
18
use League\CommonMark\Inline\Element\Text;
19
use League\CommonMark\InlineParserContext;
20
21
class NewlineParser extends AbstractInlineParser
22
{
23
    /**
24
     * @return string[]
25
     */
26 1935
    public function getCharacters()
27
    {
28 1935
        return ["\n"];
29
    }
30
31
    /**
32
     * @param InlineParserContext $inlineContext
33
     *
34
     * @return bool
35
     */
36 201
    public function parse(InlineParserContext $inlineContext)
37
    {
38 201
        $inlineContext->getCursor()->advance();
39
40
        // Check previous inline for trailing spaces
41 201
        $spaces = 0;
42 201
        $lastInline = $inlineContext->getContainer()->lastChild();
43 201
        if ($lastInline && $lastInline instanceof Text) {
44 192
            $trimmed = rtrim($lastInline->getContent(), ' ');
45 192
            $spaces = strlen($lastInline->getContent()) - strlen($trimmed);
46 192
            if ($spaces) {
47 24
                $lastInline->setContent($trimmed);
48 16
            }
49 128
        }
50
51 201
        if ($spaces >= 2) {
52 15
            $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK));
53 10
        } else {
54 186
            $inlineContext->getContainer()->appendChild(new Newline(Newline::SOFTBREAK));
55
        }
56
57 201
        return true;
58
    }
59
}
60