IPAddress::equals()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace RemotelyLiving\PHPDNS\Entities;
4
5
use RemotelyLiving\PHPDNS\Exceptions\InvalidArgumentException;
6
7
use function filter_var;
8
use function trim;
9
10
final class IPAddress extends EntityAbstract implements \Stringable
11
{
12
    private string $IPAddress;
13
14
    /**
15
     * @throws \RemotelyLiving\PHPDNS\Exceptions\InvalidArgumentException
16
     */
17
    public function __construct(string $IPAddress)
18
    {
19
        $IPAddress = trim($IPAddress);
20
21
        if (!self::isValid($IPAddress)) {
22
            throw new InvalidArgumentException("{$IPAddress} is not a valid IP address");
23
        }
24
25
        $this->IPAddress = $IPAddress;
26
    }
27
28
    public function __toString(): string
29
    {
30
        return $this->IPAddress;
31
    }
32
33
    public static function isValid(string $IPAddress): bool
34
    {
35
        return (bool) filter_var($IPAddress, FILTER_VALIDATE_IP);
36
    }
37
38
    public static function createFromString(string $IPAddress): IPAddress
39
    {
40
        return new self($IPAddress);
41
    }
42
43
    public function equals(IPAddress $IPAddress): bool
44
    {
45
        return $this->IPAddress === (string)$IPAddress;
46
    }
47
48
    public function getIPAddress(): string
49
    {
50
        return $this->IPAddress;
51
    }
52
53
    public function isIPv6(): bool
54
    {
55
        return (bool) filter_var($this->IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
56
    }
57
58
    public function isIPv4(): bool
59
    {
60
        return (bool) filter_var($this->IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
61
    }
62
}
63