Test Setup Failed
Push — master ( 860cfe...01dec1 )
by Lydia
02:35
created

IpValidator::getIp()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 48
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 38
c 0
b 0
f 0
dl 0
loc 48
rs 9.312
cc 4
nc 6
nop 1
1
<?php
2
3
namespace Anax\Model;
4
5
class IpValidator
6
{
7
    private $config;
8
    /**
9
     * Constructor, allow for $di to be injected.
10
     *
11
     * @param str $config api key
12
     */
13
    public function __construct($config)
14
    {
15
        $this->config = $config;
16
    }
17
18
    public function setConfig($config)
19
    {
20
        $this->config = $config;
21
    }
22
23
    /**
24
     *
25
     * Returns Array[valid, ip, ipv, domain], get used at view.
26
     *
27
     */
28
    public function getIp($ip) : array
29
    {
30
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
31
            $valid = "true";
32
        } else {
33
            $valid = "false";
34
        }
35
36
        if ($valid == "true") {
37
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
38
                $ipv = "Ipv4";
39
            } else {
40
                $ipv = "Ipv6";
41
            }
42
43
            $key = implode($this->config);
0 ignored issues
show
Bug introduced by
$this->config of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

43
            $key = implode(/** @scrutinizer ignore-type */ $this->config);
Loading history...
44
            $details = json_decode(file_get_contents("http://api.ipstack.com/{$ip}?access_key={$key}"));
45
46
            $domain = gethostbyaddr($ip);
47
            $lat = $details->latitude;
48
            $long = $details->longitude;
49
            $country = $details->country_name;
50
            $region = $details->region_name;
51
            $city = $details->city;
52
53
            return [
54
                "valid" => $valid,
55
                "ip" => $ip,
56
                "ipv" => $ipv,
57
                "domain" => $domain,
58
                "lat" => $lat,
59
                "long" => $long,
60
                "country" => $country,
61
                "region" => $region,
62
                "city" => $city
63
            ];
64
65
        } else {
66
            return [
67
                "valid" => "Not Valid IP",
68
                "ip" => null,
69
                "ipv" => null,
70
                "domain" => null,
71
                "lat" => null,
72
                "long" => null,
73
                "country" => null,
74
                "region" => null,
75
                "city" => null
76
            ];
77
        }
78
    }
79
}
80