Test Setup Failed
Push — master ( f21594...860cfe )
by Lydia
02:48
created

IpValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
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 Array $config for api key
12
     */
13
    public function __construct($config)
14
    {
15
        $this->config = $config;
16
    }
17
18
    /**
19
     *
20
     * Returns Array[valid, ip, ipv, domain], get used at view.
21
     *
22
     */
23
    public function toJson($ip) : array
24
    {
25
        $apiKey = $config["ip"];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to be never defined.
Loading history...
26
27
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
28
            $valid = "true";
29
        } else {
30
            $valid = "false";
31
        }
32
33
        if ($valid == "true") {
34
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
35
                $ipv = "Ipv4";
36
            } else {
37
                $ipv = "Ipv6";
38
            }
39
40
            $domain = gethostbyaddr($ip);
41
            $details = json_decode(file_get_contents("http://api.ipstack.com/{$ip}?access_key={$apiKey["key"]}"));
42
43
            $lat = $details->latitude;
44
            $long = $details->longitude;
45
            $country = $details->country_name;
46
            $region = $details->region_name;
47
            $city = $details->city;
48
49
            return [
50
                "valid" => $valid,
51
                "ip" => $ip,
52
                "ipv" => $ipv,
53
                "domain" => $domain,
54
                "lat" => $lat,
55
                "long" => $long,
56
                "country" => $country,
57
                "region" => $region,
58
                "city" => $city
59
            ];
60
61
        } else {
62
            return [
63
                "valid" => "Not Valid IP",
64
                "ip" => null,
65
                "ipv" => null,
66
                "domain" => null,
67
                "lat" => null,
68
                "long" => null,
69
                "country" => null,
70
                "region" => null,
71
                "city" => null
72
            ];
73
        }
74
    }
75
}
76