|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace RemotelyLiving\PHPDNS\Entities; |
|
4
|
|
|
|
|
5
|
|
|
use RemotelyLiving\PHPDNS\Exceptions\InvalidArgumentException; |
|
6
|
|
|
|
|
7
|
|
|
use function filter_var; |
|
8
|
|
|
use function idn_to_ascii; |
|
9
|
|
|
use function idn_to_utf8; |
|
10
|
|
|
use function mb_strtolower; |
|
11
|
|
|
use function substr; |
|
12
|
|
|
use function trim; |
|
13
|
|
|
|
|
14
|
|
|
final class Hostname extends EntityAbstract implements \Stringable |
|
15
|
|
|
{ |
|
16
|
|
|
private string $hostname; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @throws \RemotelyLiving\PHPDNS\Exceptions\InvalidArgumentException |
|
20
|
|
|
*/ |
|
21
|
|
|
public function __construct(string $hostname) |
|
22
|
|
|
{ |
|
23
|
|
|
$hostname = $this->normalizeHostName($hostname); |
|
24
|
|
|
|
|
25
|
|
|
if (filter_var($hostname, FILTER_VALIDATE_DOMAIN) !== $hostname) { |
|
26
|
|
|
throw new InvalidArgumentException("{$hostname} is not a valid hostname"); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
$this->hostname = $hostname; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function __toString(): string |
|
33
|
|
|
{ |
|
34
|
|
|
return $this->hostname; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function equals(Hostname $hostname): bool |
|
38
|
|
|
{ |
|
39
|
|
|
return $this->hostname === (string)$hostname; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public static function createFromString(string $hostname): Hostname |
|
43
|
|
|
{ |
|
44
|
|
|
return new self($hostname); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getHostName(): string |
|
48
|
|
|
{ |
|
49
|
|
|
return $this->hostname; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function getHostnameWithoutTrailingDot(): string |
|
53
|
|
|
{ |
|
54
|
|
|
return substr($this->hostname, 0, -1); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function isPunycoded(): bool |
|
58
|
|
|
{ |
|
59
|
|
|
return $this->toUTF8() !== $this->hostname; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
public function toUTF8(): string |
|
63
|
|
|
{ |
|
64
|
|
|
return (string)idn_to_utf8($this->hostname, IDNA_ERROR_PUNYCODE, INTL_IDNA_VARIANT_UTS46); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
private static function punyCode(string $hostname): string |
|
68
|
|
|
{ |
|
69
|
|
|
return (string)idn_to_ascii($hostname, IDNA_ERROR_PUNYCODE, INTL_IDNA_VARIANT_UTS46); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
private function normalizeHostName(string $hostname): string |
|
73
|
|
|
{ |
|
74
|
|
|
$hostname = self::punyCode(mb_strtolower(trim($hostname))); |
|
75
|
|
|
|
|
76
|
|
|
if (!str_ends_with($hostname, '.')) { |
|
77
|
|
|
return "{$hostname}."; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
return $hostname; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|