Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Tests

on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php: ["8.1", "8.2", "8.3", "8.4"]

steps:
- name: Checkout
uses: actions/checkout@v3

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: pcov

- name: Validate composer.json
run: composer validate --strict

- name: Install dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader

- name: Run tests
run: composer test
38 changes: 28 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# [<img src="https://ipinfo.io/static/ipinfo-small.svg" alt="IPinfo" width="24"/>](https://ipinfo.io/) IPinfo Laravel Client Library

This is the official Laravel client library for the [IPinfo.io](https://ipinfo.io) IP address API, allowing you to look up your own IP address, or get any of the following details for an IP:
- [IP geolocation](https://ipinfo.io/ip-geolocation-api) (city, region, country, postal code, latitude, and longitude)
- [ASN details](https://ipinfo.io/asn-api) (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
- [Company information](https://ipinfo.io/ip-company-api) (the name and domain of the business that uses the IP address)
- [Carrier details](https://ipinfo.io/ip-carrier-api) (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)

- [IP geolocation](https://ipinfo.io/ip-geolocation-api) (city, region, country, postal code, latitude, and longitude)
- [ASN details](https://ipinfo.io/asn-api) (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
- [Company information](https://ipinfo.io/ip-company-api) (the name and domain of the business that uses the IP address)
- [Carrier details](https://ipinfo.io/ip-carrier-api) (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)

Check all the data we have for your IP address [here](https://ipinfo.io/what-is-my-ip).

Expand All @@ -14,7 +15,7 @@ You'll need an IPinfo API access token, which you can get by signing up for a fr

The free plan is limited to 50,000 requests per month, and doesn't include some of the data fields such as IP type and company data. To enable all the data fields and additional request volumes see [https://ipinfo.io/pricing](https://ipinfo.io/pricing).

⚠️ Note: This library does not currently support our newest free API https://ipinfo.io/lite. If you’d like to use IPinfo Lite, you can call the [endpoint directly](https://ipinfo.io/developers/lite-api) using your preferred HTTP client. Developers are also welcome to contribute support for Lite by submitting a pull request.
The library also supports the Lite API, see the [Lite API section](#lite-api) for more info.

#### Installation

Expand Down Expand Up @@ -122,8 +123,8 @@ In-memory caching of `Details` data is provided by default via Laravel's file-ba

Default cache TTL and maximum size can be changed by setting values in the `$settings` argument array.

* Default maximum cache size: 4096 (multiples of 2 are recommended to increase efficiency)
* Default TTL: 24 hours (in minutes)
- Default maximum cache size: 4096 (multiples of 2 are recommended to increase efficiency)
- Default TTL: 24 hours (in minutes)

```php
'ipinfo' => [
Expand Down Expand Up @@ -223,10 +224,10 @@ By default, `ipinfolaravel` filters out requests that have `bot` or `spider` in
],
```

To set your own filtering rules, *thereby replacing the default filter*, you can set `ipinfo.config` to your own, custom callable function which satisfies the following rules:
To set your own filtering rules, _thereby replacing the default filter_, you can set `ipinfo.config` to your own, custom callable function which satisfies the following rules:

* Accepts one request.
* Returns *True to filter out, False to allow lookup*
- Accepts one request.
- Returns _True to filter out, False to allow lookup_

To use your own filter function:

Expand Down Expand Up @@ -259,6 +260,7 @@ object will be equal to `null`.
### Trying test application with Laravel Sail

Install Laravel Sail with:

```bash
cd testapp

Expand All @@ -277,6 +279,7 @@ echo "IPINFO_TOKEN=<YOUR_TOKEN>" > app/.env
```

Visit http://0.0.0.0:80. You should see a message similar to:

```
Hello world!

Expand All @@ -289,6 +292,21 @@ To run tests within `testapp` while Sail is up:
./vendor/bin/sail phpunit
```

## Lite API

The library gives the possibility to use the [Lite API](https://ipinfo.io/developers/lite-api) too, authentication with your token is still required.

The returned details are slightly different from the Core API, but it has the same configurations options.

Add the following to the `Kernel::middleware` property:

```php
protected $middleware = [
...
\ipinfo\ipinfolaravel\lite\ipinfolitelaravel::class,
];
```

### Other Libraries

There are official IPinfo client libraries available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. There are also many third-party libraries and integrations available for our API.
Expand Down
14 changes: 8 additions & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,20 @@
"homepage": "https://github.com/ipinfo/ipinfolaravel",
"keywords": ["Laravel", "ipinfolaravel"],
"require": {
"illuminate/support": ">=7",
"ipinfo/ipinfo": "^3.1.0"
"illuminate/support": "^7.0|^8.0|^9.0|^10.0|^11.0",
"ipinfo/ipinfo": "^3.2.0"
},
"require-dev": {
"phpunit/phpunit": ">=8",
"phpunit/phpunit": "^9.6",
"mockery/mockery": "^1.4.2",
"orchestra/testbench": ">=6.4.0",
"orchestra/testbench": "^8.36",
"sempro/phpunit-pretty-print": "^1.3.0",
"squizlabs/php_codesniffer": "^3.5.8"
},
"autoload": {
"psr-4": {
"ipinfo\\ipinfolaravel\\": "src/"
"ipinfo\\ipinfolaravel\\": "src/",
"ipinfo\\ipinfolaravel\\lite\\": "src/"
}
},
"autoload-dev": {
Expand All @@ -35,7 +36,8 @@
},
"scripts": {
"check-style": "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src config",
"fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src config"
"fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src config",
"test": "phpunit --colors=always --coverage-html=coverage"
},
"extra": {
"laravel": {
Expand Down
5 changes: 5 additions & 0 deletions config/ipinfolitelaravel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
//
];
2 changes: 1 addition & 1 deletion src/ipinfolaravel.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function handle($request, Closure $next)
}
}

$request->merge(['ipinfo' => $details]);
$request->attributes->set('ipinfo', $details);

return $next($request);
}
Expand Down
132 changes: 132 additions & 0 deletions src/lite/ipinfolitelaravel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace ipinfo\ipinfolaravel\lite;

use Closure;
use ipinfo\ipinfo\IPinfoLite as IPinfoLiteClient;
use ipinfo\ipinfolaravel\DefaultCache;
use ipinfo\ipinfolaravel\iphandler\DefaultIPSelector;

class ipinfolitelaravel
{
/**
* IPinfo API access token.
* @var string
*/
public $access_token = null;

/**
* IPinfo client object settings.
* @var array
*/
public $settings = [];

/**
* Return true to skip IPinfo lookup, otherwise return false.
* @var function
*/
public $filter = null;

/**
* Provides ip.
* @var ipinfo\ipinfolaravel\iphandler\IPHandlerInterface
*/
public $ip_selector = null;

const CACHE_MAXSIZE = 4096;
const CACHE_TTL = 60 * 24;

/**
* Handle an incoming request.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$this->configure();

if ($this->filter && call_user_func($this->filter, $request)) {
$details = null;
} else {
try {
$details = $this->ipinfo->getDetails(
$this->ip_selector->getIP($request),
);
} catch (\Exception $e) {
$details = null;

// users can't catch this exception with their own wrapper
// middleware unfortunately, so we catch it for them. but for
// backwards-compatibility, we throw the exception again unless
// they've told us not to.
if ($this->no_except != true) {
throw $e;
}
}
}

$request->attributes->set("ipinfo", $details);

return $next($request);
}

/**
* Determine settings based on user-defined configs or use defaults.
*/
public function configure()
{
$this->access_token = config("services.ipinfo.access_token", null);
$this->filter = config("services.ipinfo.filter", [
$this,
"defaultFilter",
]);
$this->no_except = config("services.ipinfo.no_except", false);
$this->ip_selector = config(
"services.ipinfo.ip_selector",
new DefaultIPSelector(),
);

if (
$custom_countries = config("services.ipinfo.countries_file", null)
) {
$this->settings["countries_file"] = $custom_countries;
}

if ($custom_cache = config("services.ipinfo.cache", null)) {
$this->settings["cache"] = $custom_cache;
} else {
$maxsize = config(
"services.ipinfo.cache_maxsize",
self::CACHE_MAXSIZE,
);
$ttl = config("services.ipinfo.cache_ttl", self::CACHE_TTL);
$this->settings["cache"] = new DefaultCache($maxsize, $ttl);
}

$this->ipinfo = new IPinfoLiteClient(
$this->access_token,
$this->settings,
);
}

/**
* Should IP lookup be skipped.
* @param Request $request Request object.
* @return bool Whether or not to filter out.
*/
public function defaultFilter($request)
{
$user_agent = $request->header("user-agent");
if ($user_agent) {
$lower_user_agent = strtolower($user_agent);

$is_spider = strpos($lower_user_agent, "spider") !== false;
$is_bot = strpos($lower_user_agent, "bot") !== false;

return $is_spider || $is_bot;
}

return false;
}
}
64 changes: 64 additions & 0 deletions src/lite/ipinfolitelaravelServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace ipinfo\ipinfolaravel\lite;

use Illuminate\Support\ServiceProvider;

class ipinfolitelaravelServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
* @return void
*/
public function boot()
{
// Publishing is only necessary when using the CLI.
if ($this->app->runningInConsole()) {
$this->bootForConsole();
}
}

/**
* Register any package services.
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__ . "/../../config/ipinfolitelaravel.php",
"ipinfolitelaravel",
);

// Register the service the package provides.
$this->app->singleton(
"ipinfolitelaravel",
fn($app) => new ipinfolitelaravel(),
);
}

/**
* Get the services provided by the provider.
* @return array
*/
public function provides()
{
return ["ipinfolitelaravel"];
}

/**
* Console-specific booting.
* @return void
*/
protected function bootForConsole()
{
// Publishing the configuration file.
$this->publishes(
[
__DIR__ . "/../../config/ipinfolitelaravel.php" => config_path(
"ipinfolitelaravel.php",
),
],
"ipinfolitelaravel.config",
);
}
}
Loading