Completed
Push — master ( db24e4...a24032 )
by Colin
02:01
created

PunctuationParser::parse()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 39
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 39
ccs 27
cts 27
cp 1
rs 5.3846
cc 8
eloc 26
nc 6
nop 1
crap 8
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark-extras package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (http://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\Extras\SmartPunct;
16
17
use League\CommonMark\Inline\Element\Text;
18
use League\CommonMark\Inline\Parser\AbstractInlineParser;
19
use League\CommonMark\InlineParserContext;
20
21
class PunctuationParser extends AbstractInlineParser
22
{
23
    /**
24
     * @return string[]
25
     */
26 45
    public function getCharacters()
27
    {
28 45
        return ['-', '.'];
29
    }
30
31
    /**
32
     * @param InlineParserContext $inlineContext
33
     *
34
     * @return bool
35
     */
36 36
    public function parse(InlineParserContext $inlineContext)
37
    {
38 36
        $cursor = $inlineContext->getCursor();
39 36
        $ch = $cursor->getCharacter();
40
41
        // Ellipses
42 36
        if ($ch === '.' && $matched = $cursor->match('/^\\.( ?\\.)\\1/')) {
43 3
            $inlineContext->getContainer()->appendChild(new Text('…'));
44
45 3
            return true;
46
        }
47
48
        // Em/En-dashes
49 36
        elseif ($ch === '-' && $matched = $cursor->match('/^(?<!-)(-{2,})/')) {
50 6
            $count = strlen($matched);
51 6
            $en_dash = '–';
52 6
            $en_count = 0;
53 6
            $em_dash = '—';
54 6
            $em_count = 0;
55 6
            if ($count % 3 === 0) { // If divisible by 3, use all em dashes
56 6
                $em_count = $count / 3;
57 6
            } elseif ($count % 2 === 0) { // If divisible by 2, use all en dashes
58 6
                $en_count = $count / 2;
59 6
            } elseif ($count % 3 === 2) { // If 2 extra dashes, use en dash for last 2; em dashes for rest
60 3
                $em_count = ($count - 2) / 3;
61 3
                $en_count = 1;
62 3
            } else { // Use en dashes for last 4 hyphens; em dashes for rest
63 3
                $em_count = ($count - 4) / 3;
64 3
                $en_count = 2;
65
            }
66 6
            $inlineContext->getContainer()->appendChild(new Text(
67 6
                str_repeat($em_dash, $em_count) . str_repeat($en_dash, $en_count)
68 6
            ));
69
70 6
            return true;
71
        }
72
73 33
        return false;
74
    }
75
}
76