|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Xparse\Parser\Helper; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Try to convert input encoding |
|
9
|
|
|
*/ |
|
10
|
|
|
class ToUtfConverter implements EncodingConverterInterface { |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var array|null |
|
14
|
|
|
*/ |
|
15
|
|
|
private static $supportedEncodings; |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @inheritdoc |
|
20
|
|
|
*/ |
|
21
|
|
|
public function convert(string $html, string $contentType = '') : string { |
|
22
|
|
|
$encoding = null; |
|
23
|
|
|
if ($contentType !== '') { |
|
24
|
|
|
preg_match('!^.*charset=([A-Za-z0-9-]{4,})$!', $contentType, $contentTypeData); |
|
25
|
|
|
$encoding = !empty($contentTypeData[1]) ? trim($contentTypeData[1]) : null; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
if ($encoding === null) { |
|
29
|
|
|
preg_match("!.*<meta.*charset=[\"']?[ \t]*([A-Za-z0-9-]{4,})[ \t]*[\"']!mi", $html, $metaContentType); |
|
30
|
|
|
$encoding = !empty($metaContentType[1]) ? trim($metaContentType[1]) : null; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
if ($encoding === null) { |
|
34
|
|
|
return $html; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$encoding = strtolower($encoding); |
|
38
|
|
|
if (in_array($encoding, self::getSupportedEncodings(), true)) { |
|
39
|
|
|
$html = mb_convert_encoding($html, 'utf-8', $encoding); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return $html; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @return array |
|
48
|
|
|
*/ |
|
49
|
|
|
private static function getSupportedEncodings() : array { |
|
50
|
|
|
|
|
51
|
|
|
if (self::$supportedEncodings !== null) { |
|
52
|
|
|
return self::$supportedEncodings; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$hasAliasesFunction = function_exists('mb_encoding_aliases'); |
|
56
|
|
|
self::$supportedEncodings = []; |
|
57
|
|
|
foreach (mb_list_encodings() as $encoding) { |
|
58
|
|
|
$encoding = strtolower($encoding); |
|
59
|
|
|
if ($encoding === 'utf-8' or $encoding === 'utf8') { |
|
60
|
|
|
continue; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
self::$supportedEncodings[] = $encoding; |
|
64
|
|
|
if ($hasAliasesFunction) { |
|
65
|
|
|
foreach (mb_encoding_aliases($encoding) as $encodingAlias) { |
|
66
|
|
|
$encodingAlias = strtolower($encodingAlias); |
|
67
|
|
|
self::$supportedEncodings[] = $encodingAlias; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return self::$supportedEncodings; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
} |