| 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 (https://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\CommonMark\Parser\Inline;
|
|
|
18 |
|
|
|
19 |
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
|
|
|
20 |
use League\CommonMark\Parser\Inline\InlineParserInterface;
|
|
|
21 |
use League\CommonMark\Parser\Inline\InlineParserMatch;
|
|
|
22 |
use League\CommonMark\Parser\InlineParserContext;
|
|
|
23 |
use League\CommonMark\Util\UrlEncoder;
|
|
|
24 |
|
|
|
25 |
final class AutolinkParser implements InlineParserInterface
|
|
|
26 |
{
|
|
|
27 |
private const EMAIL_REGEX = '<([a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>';
|
|
|
28 |
private const OTHER_LINK_REGEX = '<([A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*)>';
|
|
|
29 |
|
|
|
30 |
public function getMatchDefinition(): InlineParserMatch
|
|
|
31 |
{
|
|
|
32 |
return InlineParserMatch::regex(self::EMAIL_REGEX . '|' . self::OTHER_LINK_REGEX);
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
public function parse(InlineParserContext $inlineContext): bool
|
|
|
36 |
{
|
|
|
37 |
$inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
|
|
|
38 |
$matches = $inlineContext->getMatches();
|
|
|
39 |
|
|
|
40 |
if ($matches[1] !== '') {
|
|
|
41 |
$inlineContext->getContainer()->appendChild(new Link('mailto:' . UrlEncoder::unescapeAndEncode($matches[1]), $matches[1]));
|
|
|
42 |
|
|
|
43 |
return true;
|
|
|
44 |
}
|
|
|
45 |
|
|
|
46 |
if ($matches[2] !== '') {
|
|
|
47 |
$inlineContext->getContainer()->appendChild(new Link(UrlEncoder::unescapeAndEncode($matches[2]), $matches[2]));
|
|
|
48 |
|
|
|
49 |
return true;
|
|
|
50 |
}
|
|
|
51 |
|
|
|
52 |
return false; // This should never happen
|
|
|
53 |
}
|
|
|
54 |
}
|