IpValidator   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 62
rs 10
c 0
b 0
f 0
wmc 14

7 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 9 3
A __construct() 0 3 1
A getProtocolType() 0 11 3
A getPayload() 0 3 1
A getIp() 0 3 1
A getHostName() 0 11 3
A setIp() 0 5 2
1
<?php
2
3
namespace H4MSK1\IpValidator;
4
5
class IpValidator
6
{
7
    private $ipAddr;
8
    private $payload = [];
9
10
    public function __construct($ipAddr = null)
11
    {
12
        $this->setIp($ipAddr);
13
    }
14
15
    public function setIp($ipAddr = null)
16
    {
17
        $this->ipAddr = empty($ipAddr) ? 'Invalid' : $ipAddr;
18
19
        return $this;
20
    }
21
22
    public function getIp()
23
    {
24
        return $this->ipAddr;
25
    }
26
27
    public function getPayload()
28
    {
29
        return $this->payload;
30
    }
31
32
    public function validate()
33
    {
34
        $this->payload = [
35
            'ip' => $this->getIp(),
36
            'type' => $this->getProtocolType() ?: 'Invalid',
37
            'hostname' => $this->getHostName() ?: 'Unkown',
38
        ];
39
40
        return $this->payload;
41
    }
42
43
    public function getHostName()
44
    {
45
        // make sure we got a valid IP otherwise gethostbyaddr() throws an error
46
        if (! $this->getProtocolType()) {
47
            return false;
48
        }
49
50
        $ipAddr = $this->getIp();
51
        $host = gethostbyaddr($ipAddr);
52
53
        return $host === $ipAddr ? false : $host;
54
    }
55
56
    public function getProtocolType()
57
    {
58
        $ipAddr = $this->getIp();
59
60
        if (filter_var($ipAddr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
61
            return 'IPv4';
62
        } else if (filter_var($ipAddr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
63
            return 'IPv6';
64
        }
65
66
        return false;
67
    }
68
}
69