Skip to content

Commit 8323530

Browse files
ip2locationjbelien
authored andcommitted
Added IP2Location and IP2LocationBinary provider. (#1031)
* Added IP2Location and IP2LocationBinary provider. * Fixed spacing issues. * Replaced tabs into spaces. * Update src/Provider/IP2Location/IP2Location.php Co-Authored-By: atymic <[email protected]> * Updated codes and format to match Geocoder standards and requirements. * Added IP2Location API configuration. * Updated indent and formatting issues. * Updated Readme.md. * Updated Readme.md to explain IP2Location Web service credit usage. * Update Readme.md
1 parent 08099f7 commit 8323530

27 files changed

+995
-0
lines changed

phpunit.xml.dist

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
<server name="HERE_APP_CODE" value="YOUR_APP_CODE" />
2929
<server name="HERE_APP_ID" value="YOUR_APP_ID" />
3030
<server name="IPINFODB_API_KEY" value="YOUR_API_KEY" />
31+
<server name="IP2LOCATION_API_KEY" value="YOUR_API_KEY" />
3132
<server name="IPSTACK_API_KEY" value="YOUR_API_KEY" />
3233
<server name="LOCATIONIQ_API_KEY" value="YOUR_API_KEY" />
3334
<server name="MAPBOX_GEOCODING_KEY" value="YOUR_GEOCODING_KEY" />
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
.gitattributes export-ignore
2+
.travis.yml export-ignore
3+
phpunit.xml.dist export-ignore
4+
Tests/ export-ignore

src/Provider/IP2Location/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
vendor/
2+
composer.lock
3+
phpunit.xml

src/Provider/IP2Location/.travis.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
language: php
2+
sudo: false
3+
4+
php: 7.2
5+
6+
7+
install:
8+
- composer update --prefer-stable --prefer-dist
9+
10+
script:
11+
- composer test-ci
12+
13+
after_success:
14+
- wget https://scrutinizer-ci.com/ocular.phar
15+
- php ocular.phar code-coverage:upload --format=php-clover build/coverage.xml
16+

src/Provider/IP2Location/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Change Log
2+
3+
The change log describes what is "Added", "Removed", "Changed" or "Fixed" between each release.
4+
5+
## 1.0.0
6+
7+
First release of this library.
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the Geocoder package.
7+
* For the full copyright and license information, please view the LICENSE
8+
* file that was distributed with this source code.
9+
*
10+
* @license MIT License
11+
*/
12+
13+
namespace Geocoder\Provider\IP2Location;
14+
15+
use Geocoder\Exception\InvalidCredentials;
16+
use Geocoder\Exception\UnsupportedOperation;
17+
use Geocoder\Collection;
18+
use Geocoder\Model\Address;
19+
use Geocoder\Model\AddressCollection;
20+
use Geocoder\Query\GeocodeQuery;
21+
use Geocoder\Query\ReverseQuery;
22+
use Geocoder\Http\Provider\AbstractHttpProvider;
23+
use Geocoder\Provider\Provider;
24+
use Http\Client\HttpClient;
25+
26+
/**
27+
* @author William Durand <[email protected]>
28+
*/
29+
final class IP2Location extends AbstractHttpProvider implements Provider
30+
{
31+
/**
32+
* @var string
33+
*/
34+
const ENDPOINT_URL = 'https://api.ip2location.com/v2/?key=%s&ip=%s&format=json&package=WS9';
35+
36+
/**
37+
* @var string
38+
*/
39+
private $apiKey;
40+
41+
/**
42+
* @var string
43+
*/
44+
private $endpointUrl;
45+
46+
/**
47+
* @param HttpClient $client a HTTP adapter
48+
* @param string $apiKey an API key
49+
*/
50+
public function __construct(HttpClient $client, string $apiKey)
51+
{
52+
parent::__construct($client);
53+
54+
$this->apiKey = $apiKey;
55+
$this->endpointUrl = self::ENDPOINT_URL;
56+
}
57+
58+
/**
59+
* {@inheritdoc}
60+
*/
61+
public function geocodeQuery(GeocodeQuery $query): Collection
62+
{
63+
$address = $query->getText();
64+
65+
if (empty($this->apiKey)) {
66+
throw new InvalidCredentials('No API key provided.');
67+
}
68+
69+
if (!filter_var($address, FILTER_VALIDATE_IP)) {
70+
throw new UnsupportedOperation('The IP2Location provider does not support street addresses, only IP addresses.');
71+
}
72+
73+
if (in_array($address, ['127.0.0.1', '::1'])) {
74+
return new AddressCollection([$this->getLocationForLocalhost()]);
75+
}
76+
77+
$url = sprintf($this->endpointUrl, $this->apiKey, $address);
78+
79+
return $this->executeQuery($url);
80+
}
81+
82+
/**
83+
* {@inheritdoc}
84+
*/
85+
public function reverseQuery(ReverseQuery $query): Collection
86+
{
87+
throw new UnsupportedOperation('The IP2Location provider is not able to do reverse geocoding.');
88+
}
89+
90+
/**
91+
* {@inheritdoc}
92+
*/
93+
public function getName(): string
94+
{
95+
return 'ip2location';
96+
}
97+
98+
/**
99+
* @param string $url
100+
*
101+
* @return Collection
102+
*/
103+
private function executeQuery(string $url): AddressCollection
104+
{
105+
$content = $this->getUrlContents($url);
106+
$data = json_decode($content, true);
107+
108+
if (empty($data)) {
109+
return new AddressCollection([]);
110+
}
111+
112+
if (isset($data['response'])) {
113+
if (preg_match('/suspended|denied|invalid account/i', $data['response'])) {
114+
throw new InvalidCredentials('API Key provided is not valid.');
115+
} elseif (preg_match('/insufficient/i', $data['response'])) {
116+
throw new InvalidCredentials('Insufficient credits to use IP2Location service.');
117+
} elseif (preg_match('/invalid ip address/i', $data['response'])) {
118+
throw new UnsupportedOperation('Invalid IP address.');
119+
} else {
120+
throw new UnsupportedOperation('Unexpected error.');
121+
}
122+
}
123+
124+
if (isset($data['region_name'])) {
125+
$adminLevels = [[
126+
'name' => $data['region_name'],
127+
'level' => 1,
128+
]];
129+
} else {
130+
$adminLevels = [];
131+
}
132+
133+
return new AddressCollection([
134+
Address::createFromArray([
135+
'providedBy' => $this->getName(),
136+
'latitude' => $data['latitude'] ?? null,
137+
'longitude' => $data['longitude'] ?? null,
138+
'locality' => $data['city_name'] ?? null,
139+
'postalCode' => $data['zip_code'] ?? null,
140+
'adminLevels' => $adminLevels,
141+
'country' => $data['country_name'] ?? null,
142+
'countryCode' => $data['country_code'] ?? null,
143+
]),
144+
]);
145+
}
146+
}

src/Provider/IP2Location/LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2011 — William Durand <[email protected]>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

src/Provider/IP2Location/Readme.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# IP2Location Geocoder provider
2+
[![Build Status](https://travis-ci.org/geocoder-php/ip2location-provider.svg?branch=master)](http://travis-ci.org/geocoder-php/ip2location-provider)
3+
[![Latest Stable Version](https://poser.pugx.org/geocoder-php/ip2location-provider/v/stable)](https://packagist.org/packages/geocoder-php/ip2location-provider)
4+
[![Total Downloads](https://poser.pugx.org/geocoder-php/ip2location-provider/downloads)](https://packagist.org/packages/geocoder-php/ip2location-provider)
5+
[![Monthly Downloads](https://poser.pugx.org/geocoder-php/ip2location-provider/d/monthly.png)](https://packagist.org/packages/geocoder-php/ip2location-provider)
6+
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/geocoder-php/ip2location-provider.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/ip2location-provider)
7+
[![Quality Score](https://img.shields.io/scrutinizer/g/geocoder-php/ip2location-provider.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/ip2location-provider)
8+
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)
9+
10+
This is the IP2Location provider from the PHP Geocoder. This is a **READ ONLY** repository. See the
11+
[main repo](https://github.com/geocoder-php/Geocoder) for information and documentation.
12+
13+
### Install
14+
15+
```bash
16+
composer require geocoder-php/ip2location-provider
17+
```
18+
19+
### Note
20+
21+
This provider requires IP2Location™ [IP Geolocation Web Service](https://www.ip2location.com/web-service/ip2location) subscription. It is a paid solution with high accuracy. For free solution, please use our free [IpInfoDB](https://github.com/geocoder-php/Geocoder#ip) project. Ipinfodb is using [IP2Location LITE](https://lite.ip2location.com/) database which has less accuracy at city level.
22+
23+
Please note that this provider is querying IP2Location Web Service **WS9** package and each query will cost **4 credits**.
24+
25+
### Contribute
26+
27+
Contributions are very welcome! Send a pull request to the [main repository](https://github.com/geocoder-php/Geocoder) or
28+
report any issues you find on the [issue tracker](https://github.com/geocoder-php/Geocoder/issues).

src/Provider/IP2Location/Tests/.cached_responses/.gitkeep

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
s:183:"{"country_code":"US","country_name":"United States","region_name":"Oklahoma","city_name":"Tulsa","latitude":"36.15398","longitude":"-95.99278","zip_code":"74101","credits_consumed":4}";

0 commit comments

Comments
 (0)