1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Arimolzer\IPStackFinder; |
4
|
|
|
|
5
|
|
|
use Arimolzer\IPStackFinder\Exceptions\InvalidConfiguration; |
6
|
|
|
use Arimolzer\IPStackFinder\Facade\IPStackFinderFacade; |
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use Illuminate\Support\ServiceProvider; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class IPStackFinder |
12
|
|
|
* @package Arimolzer\IPStackFinder |
13
|
|
|
*/ |
14
|
|
|
class IPStackFinderServiceProvider extends ServiceProvider |
15
|
|
|
{ |
16
|
|
|
/** @var string */ |
17
|
|
|
const BASE_URI = 'http://api.ipstack.com/'; |
18
|
|
|
|
19
|
|
|
/** @var string */ |
20
|
|
|
const DEFAULT_LANGUAGE = 'en'; |
21
|
|
|
|
22
|
|
|
/** @var array $supportedLanguages */ |
23
|
|
|
private $supportedLanguages = [ |
24
|
|
|
'en', // English/US |
25
|
|
|
'de', // German |
26
|
|
|
'es', // Spanish |
27
|
|
|
'fr', // French |
28
|
|
|
'ja', // Japanese |
29
|
|
|
'pt-br', // Portugues (Brazil) |
30
|
|
|
'ru', // Russian |
31
|
|
|
'zh', // Chinese |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Bootstrap the application services. |
36
|
|
|
*/ |
37
|
|
|
public function boot() |
38
|
|
|
{ |
39
|
|
|
if ($this->app->runningInConsole()) { |
40
|
|
|
$this->publishes([ |
41
|
|
|
__DIR__.'/../config/config.php' => config_path('ipstack-finder.php'), |
42
|
|
|
], 'config'); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Register the application services. |
48
|
|
|
*/ |
49
|
|
|
public function register() |
50
|
|
|
{ |
51
|
|
|
// Automatically apply the package configuration |
52
|
|
|
$this->mergeConfigFrom(__DIR__.'/../config/config.php', 'ipstack-finder'); |
53
|
|
|
|
54
|
|
|
// Register the main class to use with the facade |
55
|
|
|
$this->app->bind('IPFinder', function () { |
56
|
|
|
$client = $this->app->make(Client::class); |
57
|
|
|
return new IPStackFinder($client); |
58
|
|
|
}); |
59
|
|
|
|
60
|
|
|
$this->app->bind(Client::class, function() { |
61
|
|
|
if (empty(config('ipstack-finder.api_key'))) { |
62
|
|
|
throw InvalidConfiguration::apiKeyNotSet(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return new Client([ |
66
|
|
|
'base_uri' => self::BASE_URI, |
67
|
|
|
'query' => [ |
68
|
|
|
'access_key' => config('ipstack-finder.api_key'), |
69
|
|
|
'language' => $this->getLanguage() |
70
|
|
|
] |
71
|
|
|
]); |
72
|
|
|
}); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Defensive programming to not give ipstack.com an invalid language param. |
77
|
|
|
* If the .env or config file provided language code is not valid, return the default. |
78
|
|
|
* @return string |
79
|
|
|
*/ |
80
|
|
|
private function getLanguage() : string |
81
|
|
|
{ |
82
|
|
|
/** @var string $defaultLanguage */ |
83
|
|
|
$defaultLanguage = config('ipstack-finder.default_language'); |
84
|
|
|
|
85
|
|
|
return (in_array($defaultLanguage, $this->supportedLanguages)) |
86
|
|
|
? $defaultLanguage : self::DEFAULT_LANGUAGE; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|