Completed
Push — master ( daaee0...0df7a1 )
by Christian
09:11
created

Hostname::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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