IP::fromString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace HtaccessFirewall\Host;
4
5
use HtaccessFirewall\Host\Exception\InvalidArgumentException;
6
7
class IP implements Host
8
{
9
    const IPV4 = 'IPv4';
10
    const IPV6 = 'IPv6';
11
12
    /**
13
     * @var string
14
     */
15
    private $value;
16
17
    /**
18
     * Initialize IP.
19
     *
20
     * @param $value
21
     *
22
     * @throws InvalidArgumentException
23
     */
24
    private function __construct($value)
25
    {
26
        if (!self::validate($value)) {
27
            throw new InvalidArgumentException('The first parameter of IP must be a valid IP address.');
28
        }
29
30
        $this->value = $value;
31
    }
32
33
    /**
34
     * Create IP from string.
35
     *
36
     * @param $string
37
     *
38
     * @return IP
39
     */
40
    public static function fromString($string)
41
    {
42
        return new self($string);
43
    }
44
45
    /**
46
     * Check if string is a valid IP.
47
     *
48
     * @param string $value
49
     *
50
     * @return bool
51
     */
52
    public static function validate($value)
53
    {
54
        return filter_var($value, FILTER_VALIDATE_IP) !== false;
55
    }
56
57
    /**
58
     * Get the version (IPv4 or IPv6) of the IP.
59
     *
60
     * @return string
61
     */
62
    public function getVersion()
63
    {
64
        $isIPv4 = filter_var($this->toString(), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
65
        if ($isIPv4 !== false) {
66
            return self::IPV4;
67
        }
68
69
        return self::IPV6;
70
    }
71
72
    /**
73
     * Compare equality with another Host.
74
     *
75
     * @param Host $other
76
     *
77
     * @return bool
78
     */
79
    public function equals(Host $other)
80
    {
81
        return $this->toString() === $other->toString();
82
    }
83
84
    /**
85
     * Get string representation of IP.
86
     *
87
     * @return string
88
     */
89
    public function toString()
90
    {
91
        return $this->value;
92
    }
93
94
    /**
95
     * Cast IP to string.
96
     *
97
     * @return string
98
     */
99
    public function __toString()
100
    {
101
        return $this->toString();
102
    }
103
}
104