|
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 null|string[] |
|
14
|
|
|
*/ |
|
15
|
|
|
private $supportedEncodings; |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @inheritdoc |
|
20
|
|
|
*/ |
|
21
|
|
|
public function convert(string $html, string $contentType = ''): string { |
|
22
|
|
|
$encoding = null; |
|
23
|
|
|
if (preg_match('!^.*charset=([A-Za-z0-9-]{4,})$!', $contentType, $contentTypeData) === 1) { |
|
24
|
|
|
$encoding = $contentTypeData[1]; |
|
25
|
|
|
} elseif (preg_match("!.*<meta.*charset=[\"']?[ \t]*([A-Za-z0-9-]{4,})[ \t]*[\"']!mi", $html, $metaContentType) === 1) { |
|
26
|
|
|
$encoding = $metaContentType[1]; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if ($encoding === null) { |
|
30
|
|
|
return $html; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$encoding = strtolower($encoding); |
|
34
|
|
|
if (in_array($encoding, $this->getSupportedEncodings(), true)) { |
|
35
|
|
|
$html = mb_convert_encoding($html, 'utf-8', $encoding); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
return $html; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return array |
|
44
|
|
|
*/ |
|
45
|
|
|
private function getSupportedEncodings(): array { |
|
46
|
|
|
if ($this->supportedEncodings === null) { |
|
47
|
|
|
$this->supportedEncodings = []; |
|
48
|
|
|
$findAliases = function_exists('mb_encoding_aliases'); |
|
49
|
|
|
foreach (mb_list_encodings() as $encoding) { |
|
50
|
|
|
$encoding = strtolower($encoding); |
|
51
|
|
|
if ($encoding !== 'utf-8' and $encoding !== 'utf8') { |
|
52
|
|
|
$this->supportedEncodings[] = $encoding; |
|
53
|
|
|
if ($findAliases) { |
|
54
|
|
|
foreach (mb_encoding_aliases($encoding) as $encodingAlias) { |
|
55
|
|
|
$encodingAlias = strtolower($encodingAlias); |
|
56
|
|
|
$this->supportedEncodings[] = $encodingAlias; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
return $this->supportedEncodings; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
} |