|
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 (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\Extension\SmartPunct; |
|
16
|
|
|
|
|
17
|
|
|
use League\CommonMark\Inline\Element\Text; |
|
18
|
|
|
use League\CommonMark\Inline\Parser\InlineParserInterface; |
|
19
|
|
|
use League\CommonMark\InlineParserContext; |
|
20
|
|
|
|
|
21
|
|
|
class PunctuationParser implements InlineParserInterface |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* @return string[] |
|
25
|
|
|
*/ |
|
26
|
51 |
|
public function getCharacters(): array |
|
27
|
|
|
{ |
|
28
|
51 |
|
return ['-', '.']; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param InlineParserContext $inlineContext |
|
33
|
|
|
* |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
36 |
|
public function parse(InlineParserContext $inlineContext): bool |
|
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
|
3 |
|
} 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
|
|
|
} 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
|
|
|
)); |
|
69
|
|
|
|
|
70
|
6 |
|
return true; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
33 |
|
return false; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|