GeoIp   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A fetchIpInfo() 0 14 2
A validateIpAddress() 0 4 2
A __construct() 0 12 3
1
<?php
2
3
namespace Src;
4
/**
5
 * Class GeoIp
6
 *
7
 * @package Src
8
 */
9
class  GeoIp extends BaseIp
10
{
11
    const INVALID_IP     = 'Invalid IP Address, please use valid one';
12
    const FAILED_REQUEST = 'Unable to retrieve data';
13
14
    private $fields = [
15
        'as',
16
        'city',
17
        'country',
18
        'countryCode',
19
        'isp',
20
        'lat',
21
        'lon',
22
        'org',
23
        'query',
24
        'region',
25
        'regionName',
26
        'status',
27
        'timezone',
28
        'zip',
29
    ];
30
31
32
    public function __construct(string $ip)
33
    {
34
        $this->validateIpAddress($ip);
35
        $data = $this->fetchIpInfo($ip);
36
37
        foreach ($data as $key => $value) {
38
            if (in_array($key, $this->fields, true)) {
39
                $this->{$key} = $value;
40
            }
41
        }
42
43
        return $this;
44
    }
45
46
    /**
47
     * validateIpAddress
48
     *
49
     *
50
     * @param string $ip
51
     *
52
     * @return void
53
     */
54
    private function validateIpAddress(string $ip)
55
    {
56
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
57
            throw new \InvalidArgumentException(self::INVALID_IP, 400);
58
        }
59
    }
60
61
62
    /**
63
     * fetchIpInfo
64
     *
65
     * @param string $ip ip
66
     *
67
     * @return array
68
     *
69
     */
70
    private function fetchIpInfo(string $ip): array
71
    {
72
        ob_start();
73
        $ch = curl_init();
74
        curl_setopt($ch, CURLOPT_URL, "http://ip-api.com/json/{$ip}");
75
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
76
        $response   = curl_exec($ch);
77
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
78
        if ($httpStatus !== 200) {
79
            throw new \Exception(self::FAILED_REQUEST);
80
        }
81
        $info = json_decode($response, true);
82
83
        return $info;
84
    }
85
}
86