/
HtmlHighlighter.php
215 lines (190 loc) · 6.1 KB
/
HtmlHighlighter.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
declare(strict_types=1);
namespace VStelmakh\UrlHighlight\Highlighter;
use InvalidArgumentException;
use VStelmakh\UrlHighlight\Matcher\UrlMatch;
use VStelmakh\UrlHighlight\Replacer\ReplacerInterface;
use VStelmakh\UrlHighlight\Util\LinkHelper;
class HtmlHighlighter implements HighlighterInterface
{
/**
* @var string
*/
private $defaultScheme;
/**
* @var string $attributes
*/
private $attributes;
/**
* @var string
*/
private $contentBefore;
/**
* @var string
*/
private $contentAfter;
/**
* @param string $defaultScheme Used to build href for urls matched without scheme
* @param array&string[] $attributes Key/value map of tag attributes, e.g.: ['rel' => 'nofollow']
* @param string $contentBefore Content to add before highlight: {here}<a...
* @param string $contentAfter Content to add after highlight: ...</a>{here}
*/
public function __construct(
string $defaultScheme = 'http',
array $attributes = [],
string $contentBefore = '',
string $contentAfter = ''
) {
$this->defaultScheme = $defaultScheme;
$this->attributes = $this->buildAttributes($attributes);
$this->contentBefore = $contentBefore;
$this->contentAfter = $contentAfter;
}
/**
* Replace all valid matches by html <a> tags
* Additional filtering done here to avoid highlight in html tags or inside a tag content
*
* @param string $string
* @param ReplacerInterface $replacer
* @return string
*/
public function highlight(string $string, ReplacerInterface $replacer): string
{
$result = '';
/** @var array&string[] $parts */
$parts = preg_split('/(<[^<>]+>)/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$isLinkContent = false;
foreach ($parts as $num => $part) {
$isTag = $num % 2 !== 0;
if ($isTag) {
$isOpenLinkTag = (bool) preg_match('/^<\s*a(?:\s|>)/iu', $part);
$isLinkContent = $isOpenLinkTag ? true : $isLinkContent;
if (!$isOpenLinkTag) {
$isCloseLinkTag = (bool) preg_match('/<\s*\/\s*a\s*>$/iu', $part);
$isLinkContent = $isCloseLinkTag ? false : $isLinkContent;
}
} elseif (!$isLinkContent) {
$part = $this->doHighlight($part, $replacer);
}
$result .= $part;
}
return $result;
}
/**
* Use replacer with callable to highlight urls
* String input at this point is not html tag or a tag content and could be safely highlighted
*
* @param string $string
* @param ReplacerInterface $replacer
* @return string
*/
protected function doHighlight(string $string, ReplacerInterface $replacer): string
{
return $replacer->replaceCallback($string, \Closure::fromCallable([$this, 'getMatchHighlight']));
}
/**
* Return html link highlight
* Example: {content before}<a href="http://example.com">http://example.com</a>{content after}
*
* @param UrlMatch $match
* @return string
*/
protected function getMatchHighlight(UrlMatch $match): string
{
$link = $this->getLink($match);
$linkSafeQuotes = str_replace('"', '%22', $link);
return sprintf(
'%s<a href="%s"%s>%s</a>%s',
$this->getContentBefore($match),
$linkSafeQuotes,
$this->getAttributes($match),
$this->getText($match),
$this->getContentAfter($match)
);
}
/**
* Link used in href attribute: <a href="{here}"...
*
* @param UrlMatch $match
* @return string
*/
protected function getLink(UrlMatch $match): string
{
return LinkHelper::getLink($match, $this->getDefaultScheme());
}
/**
* Link default scheme. Used to build href attribute
*
* @return string
*/
protected function getDefaultScheme(): string
{
return $this->defaultScheme;
}
/**
* Content used to display url: ...>{here}</a>
*
* @param UrlMatch $match
* @return string
*/
protected function getText(UrlMatch $match): string
{
return $match->getFullMatch();
}
/**
* Additional link attributes <a href="#"{here}>...
* Consider to add leading space and escape quotes, tag brackets e.g. " < > etc.
*
* @param UrlMatch $match
* @return string
*/
protected function getAttributes(UrlMatch $match): string
{
return $this->attributes;
}
/**
* Content before highlight: {here}<a...
*
* @param UrlMatch $match
* @return string
*/
protected function getContentBefore(UrlMatch $match): string
{
return $this->contentBefore;
}
/**
* Content after highlight: ...</a>{here}
*
* @param UrlMatch $match
* @return string
*/
protected function getContentAfter(UrlMatch $match): string
{
return $this->contentAfter;
}
/**
* Convert attributes array to attributes string
*
* @param array&string[] $attributes
* @return string
*/
private function buildAttributes(array $attributes): string
{
$result = [];
foreach ($attributes as $key => $value) {
// According to html5 parser spec: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
$isValidAttributeName = !preg_match_all('/[\t\n\f \/>"\'=]/', $key, $matches);
if (!$isValidAttributeName) {
$invalidChars = array_unique($matches[0]);
throw new InvalidArgumentException(sprintf(
'Attribute name %s contains invalid characters: %s',
json_encode($key),
json_encode(implode(', ', $invalidChars))
));
}
$valueSafeQuotes = str_replace('"', '"', $value);
$result[] = sprintf('%s="%s"', $key, $valueSafeQuotes);
}
return empty($result) ? '' : ' ' . implode(' ', $result);
}
}