Skip to content

Commit

Permalink
Introduce ip-api Provider
Browse files Browse the repository at this point in the history
  • Loading branch information
renanbr committed Jan 16, 2024
1 parent 9c2224f commit 1df790f
Show file tree
Hide file tree
Showing 19 changed files with 573 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ composer.phar
phpunit.xml
.phpunit.result.cache
.php-cs-fixer.cache
.php-cs-fixer.php
.puli/
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ Provider | Package | Features | Stats
[IpInfo](https://github.com/geocoder-php/ip-info-provider) | `geocoder-php/ip-info-provider` | IPv4, IPv6 <br> [Website](https://ipinfo.io/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/ip-info-provider/v/stable)](https://packagist.org/packages/geocoder-php/ip-info-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/ip-info-provider/downloads)](https://packagist.org/packages/geocoder-php/ip-info-provider)
[IpInfoDB](https://github.com/geocoder-php/ip-info-db-provider) | `geocoder-php/ip-info-db-provider` | IPv4 <br> [Website](http://ipinfodb.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/ip-info-db-provider/v/stable)](https://packagist.org/packages/geocoder-php/ip-info-db-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/ip-info-db-provider/downloads)](https://packagist.org/packages/geocoder-php/ip-info-db-provider)
[ipstack](https://github.com/geocoder-php/ipstack-provider) | `geocoder-php/ipstack-provider` | IPv4, IPv6 <br> [Website](https://ipstack.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/ipstack-provider/v/stable)](https://packagist.org/packages/geocoder-php/ipstack-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/ipstack-provider/downloads)](https://packagist.org/packages/geocoder-php/ipstack-provider)
[ip-api](https://github.com/geocoder-php/ip-api-provider) | `geocoder-php/ip-api-provider` | IPv4, IPv6 <br> [Website](https://ip-api.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/ip-api-provider/v/stable)](https://packagist.org/packages/geocoder-php/ip-api-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/ip-api-provider/downloads)](https://packagist.org/packages/geocoder-php/ip-api-provider)
[MaxMind](https://github.com/geocoder-php/maxmind-provider) | `geocoder-php/maxmind-provider` | IPv4, IPv6 <br> [Website](https://www.maxmind.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/maxmind-provider/v/stable)](https://packagist.org/packages/geocoder-php/maxmind-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/maxmind-provider/downloads)](https://packagist.org/packages/geocoder-php/maxmind-provider)
[MaxMind Binary](https://github.com/geocoder-php/maxmind-binary-provider) | `geocoder-php/maxmind-binary-provider` | IPv4, IPv6 <br> [Website](https://www.maxmind.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/maxmind-binary-provider/v/stable)](https://packagist.org/packages/geocoder-php/maxmind-binary-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/maxmind-binary-provider/downloads)](https://packagist.org/packages/geocoder-php/maxmind-binary-provider)

Expand Down
4 changes: 4 additions & 0 deletions src/Provider/IpApi/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.gitattributes export-ignore
.travis.yml export-ignore
phpunit.xml.dist export-ignore
Tests/ export-ignore
33 changes: 33 additions & 0 deletions src/Provider/IpApi/.github/workflows/provider.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Provider

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
test:
name: PHP ${{ matrix.php-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-version: ['8.0', '8.1', '8.2']
steps:
- uses: actions/checkout@v3
- name: Use PHP ${{ matrix.php-version }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: curl
- name: Validate composer.json and composer.lock
run: composer validate --strict
- name: Install dependencies
run: composer update --prefer-stable --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test-ci
- name: Upload Coverage report
run: |
wget https://scrutinizer-ci.com/ocular.phar
php ocular.phar code-coverage:upload --format=php-clover build/coverage.xml
4 changes: 4 additions & 0 deletions src/Provider/IpApi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vendor/
composer.lock
phpunit.xml
.phpunit.result.cache
7 changes: 7 additions & 0 deletions src/Provider/IpApi/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Change Log

The change log describes what is "Added", "Removed", "Changed" or "Fixed" between each release.

## 0.1.0

First release of this library.
153 changes: 153 additions & 0 deletions src/Provider/IpApi/IpApi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Geocoder\Provider\IpApi;

use Geocoder\Collection;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Model\AddressBuilder;
use Geocoder\Model\AddressCollection;
use Geocoder\Provider\IpApi\Model\IpApiLocation;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Psr\Http\Client\ClientInterface;

final class IpApi extends AbstractHttpProvider
{
private const URL = '{host_prefix}ip-api.com/json/{ip}';

private const FIELDS = 'status,message,lat,lon,city,district,zip,country,countryCode,timezone,regionName,region,proxy,hosting';

private string|null $apiKey;

public function __construct(ClientInterface $client, string $apiKey = null)
{
$this->apiKey = $apiKey;
parent::__construct($client);
}

#[\Override]
public function geocodeQuery(GeocodeQuery $query): Collection
{
$ip = $query->getText();

if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The ip-api provider does not support street addresses.');
}

if (in_array($ip, ['127.0.0.1', '::1'])) {
return new AddressCollection([$this->getLocationForLocalhost()]);
}

$url = $this->buildUrl($ip, $query->getLocale());

$body = $this->getUrlContents($url);

$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if ('fail' === $data['status']) {
$this->throwError($data['message']);
}

$location = $this->buildLocation($data);

return new AddressCollection([$location]);
}

#[\Override]
public function reverseQuery(ReverseQuery $query): Collection
{
throw new UnsupportedOperation('The ip-api provider is not able to do reverse geocoding.');
}

#[\Override]
public function getName(): string
{
return 'ip-api';
}

public function buildUrl(string $ip, string|null $locale): string
{
$baseUrl = strtr(self::URL, [
'{host_prefix}' => $this->apiKey ? 'https://pro.' : 'http://',
'{ip}' => $ip,
]);

$query = http_build_query(array_filter([
'key' => $this->apiKey,
'lang' => $locale,
'fields' => self::FIELDS,
]));

return $baseUrl.'?'.$query;
}

/**
* @param array<string, scalar> $data
*/
private function buildLocation(array $data): IpApiLocation
{
$data = array_map(
static fn ($value) => '' === $value ? null : $value,
$data,
);

$builder = new AddressBuilder($this->getName());
$builder->setCoordinates($data['lat'], $data['lon']);
$builder->setLocality($data['city']);
$builder->setSubLocality($data['district']);
$builder->setPostalCode($data['zip']);
$builder->setCountry($data['country']);
$builder->setCountryCode($data['countryCode']);
$builder->setTimezone($data['timezone']);

if ($data['regionName']) {
$builder->addAdminLevel(1, $data['regionName'], $data['region']);
}

/** @var IpApiLocation $location */
$location = $builder->build(IpApiLocation::class);

return $location
->withIsProxy($data['proxy'])
->withIsHosting($data['hosting']);
}

/**
* @see https://members.ip-api.com/faq#errors
*
* @return never
*/
private function throwError(string $message)
{
if (
in_array($message, ['private range', 'reserved range', 'invalid query'], true)
|| str_contains('Origin restriction', $message)
|| str_contains('IP range restriction', $message)
|| str_contains('Calling IP restriction', $message)
) {
throw new InvalidArgument($message);
}

if (
str_contains('invalid/expired ke', $message)
|| str_contains('no API key supplied', $message)
) {
throw new InvalidCredentials($message);
}

throw new InvalidServerResponse($message);
}
}
21 changes: 21 additions & 0 deletions src/Provider/IpApi/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2011 — William Durand <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions src/Provider/IpApi/Model/IpApiLocation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Geocoder\Provider\IpApi\Model;

use Geocoder\Model\Address;

final class IpApiLocation extends Address
{
private bool $isProxy;

private bool $isHosting;

public function isProxy(): bool
{
return $this->isProxy;
}

public function withIsProxy(bool $isProxy): self
{
$new = clone $this;
$new->isProxy = $isProxy;

return $new;
}

public function isHosting(): bool
{
return $this->isHosting;
}

public function withIsHosting(bool $isHosting): self
{
$new = clone $this;
$new->isHosting = $isHosting;

return $new;
}
}
26 changes: 26 additions & 0 deletions src/Provider/IpApi/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# ip-api Geocoder provider
[![Build Status](https://travis-ci.org/geocoder-php/ip-api-provider.svg?branch=master)](http://travis-ci.org/geocoder-php/ip-api-provider)
[![Latest Stable Version](https://poser.pugx.org/geocoder-php/ip-api-provider/v/stable)](https://packagist.org/packages/geocoder-php/ip-api-provider)
[![Total Downloads](https://poser.pugx.org/geocoder-php/ip-api-provider/downloads)](https://packagist.org/packages/geocoder-php/ip-api-provider)
[![Monthly Downloads](https://poser.pugx.org/geocoder-php/ip-api-provider/d/monthly.png)](https://packagist.org/packages/geocoder-php/ip-api-provider)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/geocoder-php/ip-api-provider.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/ip-api-provider)
[![Quality Score](https://img.shields.io/scrutinizer/g/geocoder-php/ip-api-provider.svg?style=flat-square)](https://scrutinizer-ci.com/g/geocoder-php/ip-api-provider)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)

This is the IpApi provider from the PHP Geocoder. This is a **READ ONLY** repository. See the
[main repo](https://github.com/geocoder-php/Geocoder) for information and documentation.

### Install

```bash
composer require geocoder-php/ip-api-provider
```

### Note

The default language-locale is `en`, you can choose between `de`, `es`, `pt-BR`, `fr`, `ja`, `zh-CN`, `ru`.

### Contribute

Contributions are very welcome! Send a pull request to the [main repository](https://github.com/geocoder-php/Geocoder) or
report any issues you find on the [issue tracker](https://github.com/geocoder-php/Geocoder/issues).
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
s:230:"{"status":"success","country":"United States","countryCode":"US","region":"OK","regionName":"Oklahoma","city":"Tulsa","district":"","zip":"","lat":36.15398,"lon":-95.99277,"timezone":"America/Chicago","proxy":false,"hosting":true}";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
s:230:"{"status":"success","country":"United States","countryCode":"US","region":"OK","regionName":"Oklahoma","city":"Tulsa","district":"","zip":"","lat":36.15398,"lon":-95.99277,"timezone":"America/Chicago","proxy":false,"hosting":true}";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
s:230:"{"city":"Tulsa","country":"United States","countryCode":"US","district":"","hosting":true,"lat":36.15398,"lon":-95.99277,"proxy":false,"region":"OK","regionName":"Oklahoma","status":"success","timezone":"America/Chicago","zip":""}";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
s:230:"{"city":"Tulsa","country":"United States","countryCode":"US","district":"","hosting":true,"lat":36.15398,"lon":-95.99277,"proxy":false,"region":"OK","regionName":"Oklahoma","status":"success","timezone":"America/Chicago","zip":""}";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
s:239:"{"city":"Karlskrona","country":"Sweden","countryCode":"SE","district":"","hosting":false,"lat":56.1625,"lon":15.5801,"proxy":false,"region":"K","regionName":"Blekinge County","status":"success","timezone":"Europe/Stockholm","zip":"371 37"}";
45 changes: 45 additions & 0 deletions src/Provider/IpApi/Tests/IntegrationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Geocoder\Provider\IpApi\Tests;

use Geocoder\IntegrationTest\ProviderIntegrationTest;
use Geocoder\Provider\IpApi\IpApi;
use Psr\Http\Client\ClientInterface;

class IntegrationTest extends ProviderIntegrationTest
{
protected bool $testAddress = false;

protected bool $testReverse = false;

protected bool $testIpv6 = false;

protected function createProvider(ClientInterface $httpClient): IpApi
{
return new IpApi($httpClient, $this->getApiKey());
}

protected function getCacheDir(): string
{
return __DIR__.'/.cached_responses';
}

protected function getApiKey(): string
{
if (!isset($_SERVER['IP_API_KEY'])) {
$this->markTestSkipped('No ip-api API key');
}

return $_SERVER['IP_API_KEY'];
}
}
Loading

0 comments on commit 1df790f

Please sign in to comment.