Driver   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 24
c 1
b 0
f 0
dl 0
loc 88
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getNewResponse() 0 5 1
A get() 0 11 2
A executeRequest() 0 25 1
1
<?php
2
3
namespace Psonrie\GeoLocation\Drivers;
4
5
use Psonrie\GeoLocation\Exceptions\AddressNotFoundException;
6
use Psonrie\GeoLocation\Response;
7
8
abstract class Driver
9
{
10
    /**
11
     * Returns the URL to use for querying the current driver.
12
     *
13
     * @param string $ip
14
     *
15
     * @return string
16
     */
17
    abstract protected function url($ip);
18
19
    /**
20
     * Request the specified driver for this IP.
21
     *
22
     * @param string $ip
23
     *
24
     * @return Response
25
     *
26
     * @throws AddressNotFoundException
27
     */
28
    abstract protected function request($ip);
29
30
    /**
31
     * Handle the driver request.
32
     *
33
     * @param string $ip
34
     *
35
     * @return Response|bool
36
     *
37
     * @throws AddressNotFoundException
38
     */
39
    public function get($ip)
40
    {
41
        $response = $this->request($ip);
42
43
        if (!$response->isEmpty()) {
44
            $response->ip = $ip;
45
46
            return $response;
47
        }
48
49
        return false;
50
    }
51
52
    /**
53
     * Create a new response instance.
54
     *
55
     * @return Response|mixed
56
     */
57
    protected function getNewResponse()
58
    {
59
        $response = config('geo-location.response', Response::class);
60
61
        return new $response();
62
    }
63
64
    /**
65
     * Execute request from the given URL using cURL.
66
     *
67
     * @param string $url
68
     *
69
     * @return mixed
70
     */
71
    protected function executeRequest($url)
72
    {
73
        $session = curl_init();
74
75
        curl_setopt($session, CURLOPT_URL, $url);
76
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
77
        curl_setopt($session, CURLOPT_ENCODING, "");
78
        curl_setopt($session, CURLOPT_MAXREDIRS, 10);
79
        curl_setopt($session, CURLOPT_TIMEOUT, 5);
80
        curl_setopt($session, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
81
        curl_setopt($session, CURLOPT_CUSTOMREQUEST, "GET");
82
        curl_setopt(
83
            $session,
84
            CURLOPT_HTTPHEADER,
85
            [
86
                "accept: application/json",
87
                "content-type: application/json",
88
            ]
89
        );
90
91
        $content = curl_exec($session);
92
93
        curl_close($session);
94
95
        return $content;
96
    }
97
}
98