-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMarkdownHighlighter.php
74 lines (65 loc) · 2.41 KB
/
MarkdownHighlighter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace VStelmakh\UrlHighlight\Highlighter;
use VStelmakh\UrlHighlight\Matcher\UrlMatch;
use VStelmakh\UrlHighlight\Replacer\ReplacerInterface;
class MarkdownHighlighter extends HtmlHighlighter
{
/**
* @param string $defaultScheme Used to build link for urls matched without scheme
* @param string $contentBefore Content to add before highlight: {here}[...
* @param string $contentAfter Content to add after highlight: ...){here}
*/
public function __construct(string $defaultScheme = 'http', string $contentBefore = '', string $contentAfter = '')
{
parent::__construct($defaultScheme, [], $contentBefore, $contentAfter);
}
/**
* Replace all valid matches by markdown links
* Additional filtering done here to avoid highlight in existing markdown links
*
* @param string $string
* @param ReplacerInterface $replacer
* @return string
*/
protected function doHighlight(string $string, ReplacerInterface $replacer): string
{
$result = '';
$regex = '/(
\[.+\]\([^\(\)]+\) # markdown link
| # or
(?:^|\s+)\[.+\]:\s*\S+ # markdown link reference
| # or
(?:^|\s+)\[.+\](?:$|\s+) # markdown link short
)/ux';
/** @var array&string[] $parts */
$parts = preg_split($regex, $string, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $num => $part) {
$isMarkdownLink = $num % 2 !== 0;
$result .= $isMarkdownLink
? $part
: $replacer->replaceCallback($part, \Closure::fromCallable([$this, 'getMarkdownHighlight']));
}
return $result;
}
/**
* Return markdown link highlight
* Example: [http://example.com](http://example.com)
*
* @param UrlMatch $match
* @return string
*/
private function getMarkdownHighlight(UrlMatch $match): string
{
$text = $this->getText($match);
$textSafeBrackets = str_replace(['[', ']'], ['\\[', '\\]'], $text);
$link = $this->getLink($match);
$linkSafeBrackets = str_replace(['(', ')'], ['%28', '%29'], $link);
return sprintf(
'%s[%s](%s)%s',
$this->getContentBefore($match),
$textSafeBrackets,
$linkSafeBrackets,
$this->getContentAfter($match)
);
}
}