| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
declare(strict_types=1);
|
|
|
4 |
|
|
|
5 |
/*
|
|
|
6 |
* This file is part of the league/commonmark package.
|
|
|
7 |
*
|
|
|
8 |
* (c) Colin O'Dell <colinodell@gmail.com>
|
|
|
9 |
*
|
|
|
10 |
* Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js)
|
|
|
11 |
* - (c) John MacFarlane
|
|
|
12 |
*
|
|
|
13 |
* For the full copyright and license information, please view the LICENSE
|
|
|
14 |
* file that was distributed with this source code.
|
|
|
15 |
*/
|
|
|
16 |
|
|
|
17 |
namespace League\CommonMark\Extension\SmartPunct;
|
|
|
18 |
|
|
|
19 |
use League\CommonMark\Node\Inline\Text;
|
|
|
20 |
use League\CommonMark\Parser\Inline\InlineParserInterface;
|
|
|
21 |
use League\CommonMark\Parser\Inline\InlineParserMatch;
|
|
|
22 |
use League\CommonMark\Parser\InlineParserContext;
|
|
|
23 |
|
|
|
24 |
final class DashParser implements InlineParserInterface
|
|
|
25 |
{
|
|
|
26 |
private const EN_DASH = '–';
|
|
|
27 |
private const EM_DASH = '—';
|
|
|
28 |
|
|
|
29 |
public function getMatchDefinition(): InlineParserMatch
|
|
|
30 |
{
|
|
|
31 |
return InlineParserMatch::regex('(?<!-)(-{2,})');
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
public function parse(InlineParserContext $inlineContext): bool
|
|
|
35 |
{
|
|
|
36 |
$count = $inlineContext->getFullMatchLength();
|
|
|
37 |
$inlineContext->getCursor()->advanceBy($count);
|
|
|
38 |
|
|
|
39 |
$enCount = 0;
|
|
|
40 |
$emCount = 0;
|
|
|
41 |
if ($count % 3 === 0) { // If divisible by 3, use all em dashes
|
|
|
42 |
$emCount = (int) ($count / 3);
|
|
|
43 |
} elseif ($count % 2 === 0) { // If divisible by 2, use all en dashes
|
|
|
44 |
$enCount = (int) ($count / 2);
|
|
|
45 |
} elseif ($count % 3 === 2) { // If 2 extra dashes, use en dash for last 2; em dashes for rest
|
|
|
46 |
$emCount = (int) (($count - 2) / 3);
|
|
|
47 |
$enCount = 1;
|
|
|
48 |
} else { // Use en dashes for last 4 hyphens; em dashes for rest
|
|
|
49 |
$emCount = (int) (($count - 4) / 3);
|
|
|
50 |
$enCount = 2;
|
|
|
51 |
}
|
|
|
52 |
|
|
|
53 |
$inlineContext->getContainer()->appendChild(new Text(
|
|
|
54 |
\str_repeat(self::EM_DASH, $emCount) . \str_repeat(self::EN_DASH, $enCount)
|
|
|
55 |
));
|
|
|
56 |
|
|
|
57 |
return true;
|
|
|
58 |
}
|
|
|
59 |
}
|