Address   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 99
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 99
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 9

8 Methods

Rating   Name   Duplication   Size   Complexity  
A toString() 0 3 1
A __construct() 0 3 1
A toBinary() 0 3 1
A toLong() 0 3 1
A fromLong() 0 3 1
A fromBinary() 0 3 1
A __toString() 0 3 1
A fromString() 0 7 2
1
<?php
2
3
namespace ColinODell\Ipv4;
4
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()
62
    {
63 18
        return long2ip($this->ip_long);
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)
102
    {
103 9
        $this->ip_long = $long;
104 9
    }
105
}
106