Passed
Push — master ( fc00fd...bc29a4 )
by Davide
50s
created

Ipinfo::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace DavidePastore\Ipinfo;
4
5
use DavidePastore\Ipinfo\Exception\InvalidTokenException;
6
use DavidePastore\Ipinfo\Exception\RateLimitExceedException;
7
8
/**
9
 * ipinfo.io service wrapper.
10
 *
11
 * @author davidepastore
12
 */
13
class Ipinfo
14
{
15
    /**
16
     * The base url of the ipinfo service.
17
     *
18
     * @var string
19
     */
20
    const BASE_URL = 'https://ipinfo.io/';
21
22
    /**
23
     * The ip string.
24
     *
25
     * @var string
26
     */
27
    const IP = 'ip';
28
29
    /**
30
     * The hostname string.
31
     *
32
     * @var string
33
     */
34
    const HOSTNAME = 'hostname';
35
36
    /**
37
     * The loc string.
38
     *
39
     * @var string
40
     */
41
    const LOC = 'loc';
42
43
    /**
44
     * The org string.
45
     *
46
     * @var string
47
     */
48
    const ORG = 'org';
49
50
    /**
51
     * The city string.
52
     *
53
     * @var string
54
     */
55
    const CITY = 'city';
56
57
    /**
58
     * The region string.
59
     *
60
     * @var string
61
     */
62
    const REGION = 'region';
63
64
    /**
65
     * The country string.
66
     *
67
     * @var string
68
     */
69
    const COUNTRY = 'country';
70
71
    /**
72
     * The phone string.
73
     *
74
     * @var string
75
     */
76
    const PHONE = 'phone';
77
78
    /**
79
     * The geo string.
80
     *
81
     * @var string
82
     */
83
    const GEO = 'geo';
84
85
    /**
86
     * The postal string.
87
     *
88
     * @var string
89
     */
90
    const POSTAL = 'postal';
91
92
    /**
93
     * All the settings.
94
     *
95
     * @var array
96
     */
97
    protected $settings;
98
99
    /**
100
     * Create an Ipinfo instance.
101
     *
102
     * @param array $settings An array with all the settings.
103
     *                        Supported keys are:
104
     *                        - token: string the developer token;
105
     *                        - debug: boolean active or not the debug.
106
     */
107 11
    public function __construct($settings = array())
108
    {
109
        //Merge user settings
110 11
        $this->settings = array_merge(array(
111 11
                'token' => '',
112
                'connectionTimeout' => 0,
113
                'timeout' => 0,
114
                'debug' => false,
115 11
        ), $settings);
116 11
    }
117
118
    /**
119
     * Get all the info about your own ip address.
120
     *
121
     * @return \DavidePastore\Ipinfo\Host The Host object with all the info.
122
     */
123 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...
124
    {
125 2
        $response = $this->makeCurlRequest($this::BASE_URL.'json');
126 2
        $response = $this->jsonDecodeResponse($response);
127
128 1
        return new Host($response);
129
    }
130
131
    /**
132
     * Get all the info about an ip address.
133
     *
134
     * @param string $ipAddress The ip address.
135
     *
136
     * @return \DavidePastore\Ipinfo\Host The Host object with all the info.
137
     */
138 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...
139
    {
140 2
        $response = $this->makeCurlRequest($this::BASE_URL.$ipAddress);
141 2
        $response = $this->jsonDecodeResponse($response);
142
143 2
        return new Host($response);
144
    }
145
146
    /**
147
     * Get a specific field value.
148
     *
149
     * @param string $ipAddress The ip address.
150
     * @param string $field     The field.
151
     *
152
     * @return string|\DavidePastore\Ipinfo\Host The value of the given field for the given ip.
153
     *                                           This could returns an Host object if you call it with for the field
154
     *                                           \DavidePastore\Ipinfo\Ipinfo::GEO.
155
     */
156 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...
157
    {
158 6
        $response = $this->makeCurlRequest($this::BASE_URL.$ipAddress.'/'.$field);
159 6
        $response = $this->checkGeo($field, $response);
160
161 5
        return $response;
162
    }
163
164
    /**
165
     * Get a specific field value of your own ip address.
166
     *
167
     * @param string $field The field.
168
     *
169
     * @return string|\DavidePastore\Ipinfo\Host The value of the given field for your own ip.
170
     *                                           This could returns an Host object if you call it with for the field
171
     *                                           \DavidePastore\Ipinfo\Ipinfo::GEO.
172
     */
173 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...
174
    {
175 1
        $response = $this->makeCurlRequest($this::BASE_URL.$field);
176 1
        $response = $this->checkGeo($field, $response);
177
178 1
        return $response;
179
    }
180
181
    /**
182
     * Use the /geo call to get just the geolocation information, which will often be
183
     * faster than getting the full response.
184
     *
185
     * @param string $ipAddress The ip address.
186
     *
187
     * @return \DavidePastore\Ipinfo\Host
188
     */
189 2
    public function getIpGeoDetails($ipAddress)
190
    {
191 2
        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 191 which is incompatible with the return type documented by DavidePastore\Ipinfo\Ipinfo::getIpGeoDetails of type DavidePastore\Ipinfo\Host.
Loading history...
192
    }
193
194
    /**
195
     * Check if the response is GEO and set the parameters accordingly.
196
     *
197
     * @param string $field    The field value.
198
     * @param string $response The response from the server.
199
     *
200
     * @return Ambigous <\DavidePastore\Ipinfo\Host, string> Returns an Host object if the request is
201
     *                  of the GEO type, a string otherwise. If the field value is different from the GEO type, it will
202
     *                  delete the last character ('\n').
203
     */
204 7
    private function checkGeo($field, $response)
205
    {
206 7
        if ($field == $this::GEO) {
207 2
            $response = $this->jsonDecodeResponse($response);
208 2
            $response = new Host($response);
209
        } else {
210 5
            $this->checkErrors($response);
211 4
            $response = substr($response, 0, -1);
212
        }
213
214 6
        return $response;
215
    }
216
217
    /**
218
     * Make a curl request.
219
     *
220
     * @param string $address The address of the request.
221
     *
222
     * @return string Returns the response from the request.
223
     */
224 11
    private function makeCurlRequest($address)
225
    {
226 11
        $curl = curl_init();
227
228 11
        if (!empty($this->settings['token'])) {
229 2
            $address .= '?token='.$this->settings['token'];
230
        }
231
232 11
        if ($this->settings['debug']) {
233 1
            echo 'Request address: '.$address."\n";
234
        }
235
236 11
        curl_setopt_array($curl, array(
237 11
            CURLOPT_RETURNTRANSFER => 1,
238 11
            CURLOPT_URL => $address,
239 11
            CURLOPT_CONNECTTIMEOUT => $this->settings['connectionTimeout'],
240 11
            CURLOPT_TIMEOUT => $this->settings['timeout'],
241 11
            CURLOPT_CAINFO => __DIR__ . "/cacert.pem"
242
        ));
243
244 11
        $response = curl_exec($curl);
245
246 11
        if ($response === false && $this->settings['debug']) {
247
            $error = curl_error($curl);
248
            echo "The error is".$error;
249
        }
250
251 11
        curl_close($curl);
252
253 11
        return $response;
254
    }
255
256
    /**
257
     * Returns the json decoded associative array.
258
     * @param  string $response Response from the http call.
259
     * @return array           Returns the associative array with the response.
260
     * @throws RateLimitExceedException    If you exceed the rate limit.
261
     * @throws InvalidTokenException If the used token is invalid.
262
     */
263 6
    private function jsonDecodeResponse($response)
264
    {
265 6
        if ($response) {
266
            // Check if the response contains an error message
267 5
            $this->checkErrors($response);
268 4
            $response = json_decode($response, true);
269
        } else {
270 1
            $response = array();
271
        }
272 5
        return $response;
273
    }
274
275
    /**
276
     * Check if the given response has some kind of errors.
277
     * @param string $response The response to check.
278
     * @throws RateLimitExceedException    If you exceed the rate limit.
279
     * @throws InvalidTokenException If the used token is invalid.
280
     */
281 10
    private function checkErrors($response)
282
    {
283 10
        if (strpos($response, 'Rate limit exceeded.') !== false) {
284 1
            throw new RateLimitExceedException("You exceed the rate limit.", $response);
285 9
        } elseif (strpos($response, 'Unknown token.') !== false) {
286 1
            throw new InvalidTokenException("The used token is invalid.", $response);
287
        }
288 8
    }
289
}
290