Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mckenziearts committed May 15, 2024
0 parents commit 4013171
Show file tree
Hide file tree
Showing 22 changed files with 594 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*{.yml,.yaml,.json}]
indent_size = 2
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: mckenziearts
25 changes: 25 additions & 0 deletions .github/workflows/pint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: pint

on: push

jobs:
pint:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.3
- name: Install Composer
run: composer install --no-interaction
- name: Run Laravel Pint
run: composer pint
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Apply formatting
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/node_modules
/vendor
.idea
.DS_Store
composer.lock
.phpunit.result.cache
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Arthur Monney

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.
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# [<img src="https://assets-global.website-files.com/65166126ca18241731aa26b0/65390de624cb65770560dda5_FAV.png" alt="Abstract API" width="24"/>](https://www.abstractapi.com) Abstract’s IP Geolocation API Laravel Client Library

### Getting Started

Abstract’s IP Geolocation API is a fast, lightweight, modern, and RESTful JSON API for determining the location and other details of IP addresses from over 190 countries.

The free plan is limited to 1,000 requests per month. To enable all the data fields and additional request volumes see [https://www.abstractapi.com/api/ip-geolocation-api#pricing](https://www.abstractapi.com/api/ip-geolocation-api#pricing).

### Installation

The package works with PHP 8 and is available using [Composer](https://getcomposer.org).

```shell
composer require laravelcm/abstract-ip-geolocation
```

### Usage

Open your application's `\app\Http\Kernel.php` file and add the following to the `Kernel::middleware` property:

```php
protected $middleware = [
...
\Laravelcm\AbstractIpGeolocation\Middleware\AbstractIpGeolocation::class,
];
```

#### Quick Start

```php
Route::get('/', function () {
$location = "The IP address " . request()->get('abstract-ip-geolocation')['ip_address'];
return view('index', ['location' => $location]);
});
```

Will return the following string to the `index` view:

```shell
"The IP address 127.0.0.1."
```

### Configuration

wip..
56 changes: 56 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "laravelcm/abstract-ip-geolocation",
"description": "Abstract’s IP Geolocation API is a fast, lightweight, modern, and RESTful JSON API for determining the location and other details of IP addresses from over 190 countries.",
"license": "MIT",
"keywords": [
"laravel",
"ip-geolocation",
"abstract-api"
],
"authors": [
{
"name": "Arthur Monney",
"email": "[email protected]"
}
],
"require": {
"php": "^8.2",
"ext-json": "*",
"illuminate/support": "^10.0|^11.0",
"spatie/laravel-package-tools": "^1.15"
},
"require-dev": {
"orchestra/testbench": "^8.5",
"laravel/pint": "^1.1",
"pestphp/pest": "^2.34",
"mockery/mockery": "^1.6"
},
"autoload": {
"psr-4": {
"Laravelcm\\AbstractIpGeolocation\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Laravelcm\\AbstractIpGeolocation\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"Laravelcm\\AbstractIpGeolocation\\AbstractIpGeolocationServiceProvider"
]
}
},
"scripts": {
"test": "vendor/bin/pest",
"pint": "vendor/bin/pint"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
}
}
}
92 changes: 92 additions & 0 deletions config/abstract-ip-geolocation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

use Laravelcm\AbstractIpGeolocation\IpSelector;

return [

/*
|--------------------------------------------------------------------------
| API Key
|--------------------------------------------------------------------------
|
|
*/

'api_key' => env('ABSTRACT_IP_GEOLOCATION_API_KEY'),

/*
|--------------------------------------------------------------------------
| User IP Address
|--------------------------------------------------------------------------
| By default, Abstract IP Geolocation will detect the ip address. But you can
| update this configuration to include the client's ip address every time.
|
| If this value is set to "true", the ip will be detected using the "ip_selector" config.
|
*/

'include_ip' => false,

/*
|--------------------------------------------------------------------------
| Geolocation Fields
|--------------------------------------------------------------------------
| You can include a fields value in the query parameters with a comma
| separated list of the top-level keys you want to be returned. For example
| "fields => 'city,region'" will return only the city and region in the response.
|
| see: https://docs.abstractapi.com/ip-geolocation#request-parameters
*/

'fields' => null,

/*
|--------------------------------------------------------------------------
| Ip Selector Class
|--------------------------------------------------------------------------
| You can select which class will be used to retrieve the client's ip address
| or you can change it and use your own class to return the ip address.
|
| In case you use a custom IP selector, you may implement the
| \Laravelcm\AbstractIpGeolocation\Contracts\AbstractIpInterface interface
|
| Available class: "IpSelector", "OriginatingIpSelector"
|
*/

'ip_selector' => new IpSelector(),

/*
|--------------------------------------------------------------------------
| Cache HTTP Request API
|--------------------------------------------------------------------------
|
|
*/

'cache' => [
/*
| By default, requests are cached to retrieve the user's ip.
| If you use the "Free plan" option, caching can help you save
| on requests to the Abstract IP Geolocation API.
*/

'enable' => true,

/*
|
*/

'maxsize' => 5,

/*
|
|
*/

'ttl' => 86400,
],

];
17 changes: 17 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>
8 changes: 8 additions & 0 deletions pint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"presets": "laravel",
"rules": {
"concat_space": {
"spacing": "one"
}
}
}
63 changes: 63 additions & 0 deletions src/AbstractIpGeolocation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace Laravelcm\AbstractIpGeolocation;

use Illuminate\Support\Facades\Http;
use Laravelcm\AbstractIpGeolocation\Exceptions\AbstractApiGeolocationException;

final class AbstractIpGeolocation
{
public function __construct(
public string $token,
public ?string $fields = null,
public ?DefaultCache $cache = null
) {
}

public function details(?string $ipAddress = null): array
{
if ($this->cache) {
$cacheResponse = $this->cache->get($this->cacheKey($ipAddress ?? '-1'));

if ($cacheResponse !== null) {
return $cacheResponse;
}
}

try {
$response = Http::withHeaders([
'content-type' => 'application/json',
'accept' => 'application/json',
])
->get('https://ipgeolocation.abstractapi.com/v1', [
'api_key' => $this->token,
'ip_address' => $ipAddress,
'fields' => $this->fields,
]);
} catch (\Exception $e) {
throw new AbstractApiGeolocationException($e->getMessage());
}

if ($response->status() === 422) {
throw new AbstractApiGeolocationException('The request was aborted due to insufficient API credits. (Free plan)');
} elseif ($response->status() >= 400) {
throw new AbstractApiGeolocationException('Exception: ' . json_encode([
'status' => $response->status(),
'message' => $response->body(),
]));
}

$result = $response->json();

$this->cache?->set($this->cacheKey($ipAddress ?? '-1'), $result);

return $result;
}

protected function cacheKey(string $key): string
{
return sprintf('%s_v%s', $key, '-1');
}
}
17 changes: 17 additions & 0 deletions src/AbstractIpGeolocationServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Laravelcm\AbstractIpGeolocation;

use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;

final class AbstractIpGeolocationServiceProvider extends PackageServiceProvider
{
public function configurePackage(Package $package): void
{
$package->name('abstract-ip-geolocation')
->hasConfigFile();
}
}
15 changes: 15 additions & 0 deletions src/Contracts/AbstractIpInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Laravelcm\AbstractIpGeolocation\Contracts;

interface AbstractIpInterface
{
/**
* Get IP address of the current visitor.
*
* @param \Illuminate\Http\Request $request
*/
public function getIpAddress($request): string;
}
Loading

0 comments on commit 4013171

Please sign in to comment.