Skip to content

Commit

Permalink
Hello Yii2 IpStack
Browse files Browse the repository at this point in the history
  • Loading branch information
glpzzz committed Aug 22, 2021
0 parents commit 5e2c4b9
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 0 deletions.
41 changes: 41 additions & 0 deletions Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace daxslab\ipstack;

use Yii;
use yii\base\Component;
use yii\base\InvalidArgumentException;

/**
* This is just an example.
*/
class Client extends Component
{
public $api_key = null;

protected $base_url = 'http://api.ipstack.com/{ip}?access_key={key}';

public function init()
{
parent::init();
if ($this->api_key === null) {
throw new InvalidArgumentException(Yii::t('app', 'API key can\'t be null.'));
}
}

public function getData($ip = null)
{
$searchIp = $ip ?? \Yii::$app->request->userIP;
try {
$url = str_replace(['{ip}', '{key}'], [$searchIp, $this->api_key], $this->base_url);
return json_decode(file_get_contents($url), true);
} catch (\Exception $e) {
Yii::error(serialize([
'message' => $e->getMessage(),
'ip' => $searchIp,
]), __METHOD__);
return null;
}
}

}
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
Yii2 IPStack Client
===================
Locate and identify website visitors by IP address using IPStack API

Installation
------------

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist daxslab/yii2-ipstack "*"
```

or add

```
"daxslab/yii2-ipstack": "*"
```

to the require section of your `composer.json` file.


Configuration
-------------

Add the component to the application:

```php
'components' => [
'ipStack' => [
'class' => \daxslab\ipstack\Client::class,
'api_key' => '{YOUR_API_KEY}',
],
]
```

Usage
-----

Request info about current user IP

```php
Yii::$app->ipStack->getData();
```

Request info about a custom IP

```php
Yii::$app->ipStack->getData($ip);
```
21 changes: 21 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "daxslab/yii2-ipstack",
"description": "Locate and identify website visitors by IP address ",
"type": "yii2-extension",
"keywords": ["yii2","extension"," ip"," ipstack"," geo"," geolocalization"],
"license": "MIT",
"authors": [
{
"name": "Daxslab",
"email": "[email protected]"
}
],
"require": {
"yiisoft/yii2": "~2.0.0"
},
"autoload": {
"psr-4": {
"daxslab\\ipstack\\": ""
}
}
}

0 comments on commit 5e2c4b9

Please sign in to comment.