Completed
Pull Request — master (#53)
by Davide
04:15 queued 02:19
created

Ipinfo::makeCurlRequest()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6.0702

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 21
cts 24
cp 0.875
rs 8.6417
c 0
b 0
f 0
cc 6
nc 24
nop 1
crap 6.0702
1
<?php
2
3
namespace DavidePastore\Ipinfo;
4
5
use DavidePastore\Ipinfo\Exception\InvalidTokenException;
6
use DavidePastore\Ipinfo\Exception\IpInfoException;
7
use DavidePastore\Ipinfo\Exception\RateLimitExceedException;
8
use DavidePastore\Ipinfo\Exception\WrongIpException;
9
10
/**
11
 * ipinfo.io service wrapper.
12
 *
13
 * @author davidepastore
14
 */
15
class Ipinfo
16
{
17
    /**
18
     * The base url of the ipinfo service.
19
     *
20
     * @var string
21
     */
22
    const BASE_URL = 'https://ipinfo.io/';
23
24
    /**
25
     * The ip string.
26
     *
27
     * @var string
28
     */
29
    const IP = 'ip';
30
31
    /**
32
     * The hostname string.
33
     *
34
     * @var string
35
     */
36
    const HOSTNAME = 'hostname';
37
38
    /**
39
     * The loc string.
40
     *
41
     * @var string
42
     */
43
    const LOC = 'loc';
44
45
    /**
46
     * The org string.
47
     *
48
     * @var string
49
     */
50
    const ORG = 'org';
51
52
    /**
53
     * The city string.
54
     *
55
     * @var string
56
     */
57
    const CITY = 'city';
58
59
    /**
60
     * The region string.
61
     *
62
     * @var string
63
     */
64
    const REGION = 'region';
65
66
    /**
67
     * The country string.
68
     *
69
     * @var string
70
     */
71
    const COUNTRY = 'country';
72
73
    /**
74
     * The phone string.
75
     *
76
     * @var string
77
     */
78
    const PHONE = 'phone';
79
80
    /**
81
     * The geo string.
82
     *
83
     * @var string
84
     */
85
    const GEO = 'geo';
86
87
    /**
88
     * The postal string.
89
     *
90
     * @var string
91
     */
92
    const POSTAL = 'postal';
93
94
    /**
95
     * All the settings.
96
     *
97
     * @var array
98
     */
99
    protected $settings;
100
101
    /**
102
     * Create an Ipinfo instance.
103
     *
104
     * @param array $settings An array with all the settings.
105
     *                        Supported keys are:
106
     *                        - token: string the developer token;
107 11
     *                        - debug: boolean active or not the debug.
108
     */
109
    public function __construct($settings = array())
110 11
    {
111 11
        //Merge user settings
112 11
        $this->settings = array_merge(array(
113 11
                'token' => '',
114 11
                'debug' => false,
115 11
                'curlOptions' => array()
116
        ), $settings);
117
    }
118
119
    /**
120
     * Get all the info about your own ip address.
121
     *
122
     * @return \DavidePastore\Ipinfo\Host The Host object with all the info.
123
     * @throws InvalidTokenException
124 2
     * @throws RateLimitExceedException
125
     */
126 2 View Code Duplication
    public function getYourOwnIpDetails()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127 2
    {
128
        $response = $this->makeCurlRequest($this::BASE_URL.'json');
129 1
        $response = $this->jsonDecodeResponse($response);
130
131
        return new Host($response);
132
    }
133
134
    /**
135
     * Get all the info about an ip address.
136
     *
137
     * @param string $ipAddress The ip address.
138
     *
139
     * @return \DavidePastore\Ipinfo\Host The Host object with all the info.
140
     * @throws InvalidTokenException
141 2
     * @throws RateLimitExceedException
142
     */
143 2 View Code Duplication
    public function getFullIpDetails($ipAddress)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144 2
    {
145
        $response = $this->makeCurlRequest($this::BASE_URL.$ipAddress);
146 2
        $response = $this->jsonDecodeResponse($response);
147
148
        return new Host($response);
149
    }
150
151
    /**
152
     * Get a specific field value.
153
     *
154
     * @param string $ipAddress The ip address.
155
     * @param string $field The field.
156
     *
157
     * @return string|\DavidePastore\Ipinfo\Host The value of the given field for the given ip.
158
     *                                           This could returns an Host object if you call it with for the field
159
     *                                           \DavidePastore\Ipinfo\Ipinfo::GEO.
160
     * @throws InvalidTokenException
161 6
     * @throws RateLimitExceedException
162
     */
163 6 View Code Duplication
    public function getSpecificField($ipAddress, $field)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164 6
    {
165
        $response = $this->makeCurlRequest($this::BASE_URL.$ipAddress.'/'.$field);
166 5
        $response = $this->checkGeo($field, $response);
167
168
        return $response;
169
    }
170
171
    /**
172
     * Get a specific field value of your own ip address.
173
     *
174
     * @param string $field The field.
175
     *
176
     * @return string|\DavidePastore\Ipinfo\Host The value of the given field for your own ip.
177
     *                                           This could returns an Host object if you call it with for the field
178
     *                                           \DavidePastore\Ipinfo\Ipinfo::GEO.
179
     * @throws InvalidTokenException
180 1
     * @throws RateLimitExceedException
181
     */
182 1 View Code Duplication
    public function getYourOwnIpSpecificField($field)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183 1
    {
184
        $response = $this->makeCurlRequest($this::BASE_URL.$field);
185 1
        $response = $this->checkGeo($field, $response);
186
187
        return $response;
188
    }
189
190
    /**
191
     * Use the /geo call to get just the geolocation information, which will often be
192
     * faster than getting the full response.
193
     *
194
     * @param string $ipAddress The ip address.
195
     *
196
     * @return \DavidePastore\Ipinfo\Host
197
     * @throws InvalidTokenException
198 2
     * @throws RateLimitExceedException
199
     */
200 2
    public function getIpGeoDetails($ipAddress)
201
    {
202
        return $this->getSpecificField($ipAddress, $this::GEO);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->getSpecificField($ipAddress, $this::GEO); of type string|DavidePastore\Ipinfo\Host adds the type string to the return on line 202 which is incompatible with the return type documented by DavidePastore\Ipinfo\Ipinfo::getIpGeoDetails of type DavidePastore\Ipinfo\Host.
Loading history...
203
    }
204
205
    /**
206
     * Check if the response is GEO and set the parameters accordingly.
207
     *
208
     * @param string $field The field value.
209
     * @param string $response The response from the server.
210
     *
211
     * @return \DavidePastore\Ipinfo\Host|string Returns an Host object if the request is
212
     *                  of the GEO type, a string otherwise. If the field value is different from the GEO type, it will
213
     *                  delete the last character ('\n').
214
     * @throws InvalidTokenException
215 7
     * @throws RateLimitExceedException
216
     */
217 7
    private function checkGeo($field, $response)
218 2
    {
219 2
        if ($field == $this::GEO) {
220 2
            $response = $this->jsonDecodeResponse($response);
221 5
            $response = new Host($response);
222 4
        } else {
223
            $this->checkErrors($response);
224
            $response = substr($response, 0, -1);
225 6
        }
226
227
        return $response;
228
    }
229
230
    /**
231
     * Make a curl request.
232
     *
233
     * @param string $address The address of the request.
234
     *
235 11
     * @return string Returns the response from the request.
236
     */
237 11
    private function makeCurlRequest($address)
238
    {
239 11
        $curl = curl_init();
240 2
241 2
        if (!empty($this->settings['token'])) {
242
            $address .= '?token='.$this->settings['token'];
243 11
        }
244 1
245 1
        if ($this->settings['debug']) {
246
            echo 'Request address: '.$address."\n";
247 11
        }
248 11
249 11
        curl_setopt_array(
250 11
            $curl,
251
            array_replace(
252 11
                $this->settings['curlOptions'],
253 11
                array(
254 11
                    CURLOPT_RETURNTRANSFER => 1,
255 11
                    CURLOPT_URL => $address
256 11
                )
257
            )
258 11
        );
259
260 11
        $response = curl_exec($curl);
261
262
        if (curl_errno($curl)) {
263
            $errorMessage = curl_error($curl);
264
265 11
            if ($this->settings['debug']) {
266
                echo "The error is".$errorMessage;
267 11
            }
268
        }
269
270
        if (isset($errorMessage)) {
271
            throw new IpInfoException('cURL error', $errorMessage);
272
        }
273
274
        curl_close($curl);
275
276
        return $response;
277 6
    }
278
279 6
    /**
280
     * Returns the json decoded associative array.
281 5
     * @param  string $response Response from the http call.
282 4
     * @return array           Returns the associative array with the response.
283 4
     * @throws RateLimitExceedException    If you exceed the rate limit.
284 1
     * @throws InvalidTokenException If the used token is invalid.
285
     */
286 5
    private function jsonDecodeResponse($response)
287
    {
288
        if ($response) {
289
            // Check if the response contains an error message
290
            $this->checkErrors($response);
291
            $response = json_decode($response, true);
292
        } else {
293
            $response = array();
294
        }
295 10
        return $response;
296
    }
297 10
298 1
    /**
299 9
     * Check if the given response has some kind of errors.
300 1
     * @param string $response The response to check.
301
     * @throws RateLimitExceedException    If you exceed the rate limit.
302 8
     * @throws InvalidTokenException If the used token is invalid.
303
     * @throws WrongIpException If the used token is invalid.
304 1
     */
305
    private function checkErrors($response)
306
    {
307
        if (strpos($response, 'Rate limit exceeded.') !== false) {
308
            throw new RateLimitExceedException("You exceed the rate limit.", $response);
309
        } elseif (strpos($response, 'Unknown token') !== false) {
310
            throw new InvalidTokenException("The used token is invalid.", $response);
311
        } elseif (strpos($response, 'Wrong ip') !== false) {
312
            throw new WrongIpException("The used IP address is not valid.", $response);
313
        }
314
    }
315
}
316