Total Complexity | 9 |
Total Lines | 99 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | <?php |
||
5 | class Address |
||
6 | { |
||
7 | /** |
||
8 | * @var int |
||
9 | */ |
||
10 | private $ip_long; |
||
11 | |||
12 | const ERROR_ADDR_FORMAT = 'IP address string format error'; |
||
13 | |||
14 | /** |
||
15 | * Create Address object from a standard dotted-quad IP address. |
||
16 | * |
||
17 | * @param string $data |
||
18 | * |
||
19 | * @throws \InvalidArgumentException |
||
20 | * |
||
21 | * @return self |
||
22 | */ |
||
23 | 15 | public static function fromString($data) |
|
24 | { |
||
25 | 15 | if ($long = ip2long($data)) { |
|
26 | 12 | return new self($long); |
|
27 | } |
||
28 | |||
29 | 3 | throw new \InvalidArgumentException(self::ERROR_ADDR_FORMAT); |
|
30 | } |
||
31 | |||
32 | /** |
||
33 | * Create Address object from a decimal (long) address. |
||
34 | * |
||
35 | * @param int $data |
||
36 | * |
||
37 | * @return self |
||
38 | */ |
||
39 | 12 | public static function fromLong($data) |
|
40 | { |
||
41 | 12 | return new self((float) $data); |
|
42 | } |
||
43 | |||
44 | /** |
||
45 | * Create Address object from a binary address. |
||
46 | * |
||
47 | * @param string $data |
||
48 | * |
||
49 | * @return self |
||
50 | */ |
||
51 | 12 | public static function fromBinary($data) |
|
52 | { |
||
53 | 12 | return new self(bindec($data)); |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * Return value as dotted quad IP address. |
||
58 | * |
||
59 | * @return string |
||
60 | */ |
||
61 | 18 | public function toString() |
|
64 | } |
||
65 | |||
66 | /** |
||
67 | * Return value as decimal (long) address. |
||
68 | * |
||
69 | * @return float |
||
70 | */ |
||
71 | 12 | public function toLong() |
|
72 | { |
||
73 | 12 | return $this->ip_long; |
|
74 | } |
||
75 | |||
76 | /** |
||
77 | * Return binary representation of address. |
||
78 | * |
||
79 | * @return string |
||
80 | */ |
||
81 | 12 | public function toBinary() |
|
82 | { |
||
83 | 12 | return str_pad(decbin($this->ip_long), 32, 0, STR_PAD_LEFT); |
|
84 | } |
||
85 | |||
86 | /** |
||
87 | * Return dotted quad IP address. |
||
88 | * |
||
89 | * @return string |
||
90 | */ |
||
91 | 3 | public function __toString() |
|
92 | { |
||
93 | 3 | return $this->toString(); |
|
94 | } |
||
95 | |||
96 | /** |
||
97 | * Private constructor. |
||
98 | * |
||
99 | * @param float $long |
||
100 | */ |
||
101 | 9 | private function __construct($long) |
|
104 | 9 | } |
|
105 | } |
||
106 |