1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* (c) Christian Gripp <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Core23\Twig\Extension; |
13
|
|
|
|
14
|
|
|
use Twig\Extension\AbstractExtension; |
15
|
|
|
use Twig\TwigFilter; |
16
|
|
|
|
17
|
|
|
final class UrlAutoConverterTwigExtension extends AbstractExtension |
18
|
|
|
{ |
19
|
|
|
public function getFilters() |
20
|
|
|
{ |
21
|
|
|
return [ |
22
|
|
|
new TwigFilter('converturls', [$this, 'convertLinks'], [ |
23
|
|
|
'is_safe' => ['html'], |
24
|
|
|
]), |
25
|
|
|
]; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function convertLinks(string $text, array $options = []): string |
29
|
|
|
{ |
30
|
|
|
$text = $this->replaceProtocol($text); |
31
|
|
|
$ret = ' '.$text; |
32
|
|
|
|
33
|
|
|
$attr = ''; |
34
|
|
|
foreach ($options as $key => $value) { |
35
|
|
|
$attr .= ' '.$key.'="'.$value.'"'; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
// Replace Links with http:// |
39
|
|
|
$ret = (string) preg_replace("#(^|[\n ])([\\w]+?://[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="\\2"'.$attr.'>\\2</a>', $ret); |
40
|
|
|
|
41
|
|
|
// Replace Links without http:// |
42
|
|
|
$ret = (string) preg_replace("#(^|[\n ])((www|ftp)\\.[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="http://\\2"'.$attr.'>\\2</a>', $ret); |
43
|
|
|
|
44
|
|
|
// Replace Email Addresses |
45
|
|
|
$ret = (string) preg_replace("#(^|[\n ])([a-z0-9&\\-_.]+?)@([\\w\\-]+\\.([\\w\\-\\.]+\\.)*[\\w]+)#i", '\\1<a href="mailto:\\2@\\3"'.$attr.'>\\2@\\3</a>', $ret); |
46
|
|
|
|
47
|
|
|
return substr($ret, 1); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @see https://bitbucket.org/kwi/urllinker/ |
52
|
|
|
*/ |
53
|
|
|
private function replaceProtocol(string $text): string |
54
|
|
|
{ |
55
|
|
|
return preg_replace('#(script|about|applet|activex|chrome):#is', '\\1:', $text) ?: ''; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|