IpUtil::validateIp()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 8
nc 4
nop 1
crap 6
1
<?php
2
3
namespace Ip2c\Ip;
4
5
class IpUtil
6
{
7
    /**
8
     * A*256^3 + B*256^2 + C*256 + D
9
     * @param string $ip
10
     * @return int|bool
11
     */
12 12
    public function ip2long($ip)
13
    {
14 12
        if (!$this->validateIp($ip)) {
15 1
            return false;
16
        }
17
18 11
        $parts = explode('.', $ip);
19 11
        $sumParts = array();
20 11
        $partIndex = 0;
21 11
        for ($exponent = 3; $exponent >= 0; $exponent--) {
22 11
            $sumParts[] = pow(256, $exponent) * $parts[$partIndex];
23 11
            $partIndex++;
24 11
        }
25
26 11
        return array_sum($sumParts);
27
    }
28
29 12
    private function validateIp($ipV4)
30
    {
31 12
        $parts = explode('.', $ipV4);
32 12
        if (count($parts) != 4) {
33 1
            return false;
34
        }
35
36 12
        foreach ($parts as $part) {
37 12
            if ($part < 0 || $part > 255 || !$part) {
38 1
                return false;
39
            }
40 12
        }
41
42 11
        return true;
43
    }
44
}
45