1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Pdp; |
6
|
|
|
|
7
|
|
|
use TrueBV\Punycode; |
8
|
|
|
|
9
|
|
|
class PunycodeWrapper |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var Punycode |
13
|
|
|
*/ |
14
|
|
|
private static $punycode; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
private $idnSupport = false; |
20
|
|
|
|
21
|
14 |
|
public function __construct() |
22
|
|
|
{ |
23
|
|
|
if ( |
24
|
14 |
|
\function_exists('idn_to_ascii') |
25
|
|
|
&& |
26
|
14 |
|
\function_exists('idn_to_utf8') |
27
|
|
|
) { |
28
|
14 |
|
$this->idnSupport = true; |
29
|
|
|
|
30
|
14 |
|
return; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
if (self::$punycode === null) { |
34
|
|
|
self::$punycode = new Punycode(); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Encode a domain to its Punycode version |
40
|
|
|
* |
41
|
|
|
* @param string $input Domain name in Unicode to be encoded |
42
|
|
|
* |
43
|
|
|
* @return string Punycode representation in ASCII |
44
|
|
|
*/ |
45
|
13 |
View Code Duplication |
public function encode($input): string |
|
|
|
|
46
|
|
|
{ |
47
|
13 |
|
if ($this->idnSupport === true) { |
48
|
|
|
// https://git.ispconfig.org/ispconfig/ispconfig3/blob/master/interface/lib/classes/functions.inc.php#L305 |
49
|
13 |
|
if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46') && constant('IDNA_NONTRANSITIONAL_TO_ASCII')) { |
50
|
13 |
|
return idn_to_ascii($input, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); |
51
|
|
|
} else { |
52
|
|
|
return idn_to_ascii($input); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return self::$punycode->encode($input); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Decode a Punycode domain name to its Unicode counterpart |
61
|
|
|
* |
62
|
|
|
* @param string $input Domain name in Punycode |
63
|
|
|
* |
64
|
|
|
* @return string Unicode domain name |
65
|
|
|
*/ |
66
|
11 |
View Code Duplication |
public function decode($input): string |
|
|
|
|
67
|
|
|
{ |
68
|
11 |
|
if ($this->idnSupport === true) { |
69
|
11 |
|
if (defined('IDNA_NONTRANSITIONAL_TO_UNICODE') && defined('INTL_IDNA_VARIANT_UTS46') && constant('IDNA_NONTRANSITIONAL_TO_UNICODE')) { |
70
|
11 |
|
return idn_to_utf8($input, IDNA_NONTRANSITIONAL_TO_UNICODE, INTL_IDNA_VARIANT_UTS46); |
71
|
|
|
} else { |
72
|
|
|
return idn_to_utf8($input); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return self::$punycode->decode($input); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.