Completed
Push — master ( fa86f6...fd256f )
by Ari
01:13
created

IPStackFinder   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 2
cbo 2
dl 0
loc 69
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A get() 0 11 1
A getLanguage() 0 8 2
1
<?php
2
3
namespace Arimolzer\IPStackFinder;
4
5
use GuzzleHttp\Client;
6
7
/**
8
 * Class IPStackFinder
9
 * @package Arimolzer\IPStackFinder
10
 */
11
class IPStackFinder
12
{
13
    /** @var string */
14
    const BASE_URI = 'http://api.ipstack.com/';
15
16
    /** @var string */
17
    const DEFAULT_LANGUAGE = 'en';
18
19
    /** @var Client $client */
20
    public $client;
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
     * IPStackHelper constructor.
36
     */
37
    public function __construct()
38
    {
39
        $this->client = new Client([
40
            'base_uri' => self::BASE_URI,
41
            'query' => [
42
                'access_key' => config('ipstack-finder.api_key'),
43
                'language' => $this->getLanguage()
44
            ]
45
        ]);
46
    }
47
48
    /**
49
     * Get the API response from ipstack.com and return in php associative array format.
50
     * @param $ipAddress
51
     * @return array
52
     * @throws \GuzzleHttp\Exception\GuzzleException
53
     */
54
    public function get($ipAddress) : array
55
    {
56
        /** @var string $responseJson */
57
        $responseJson = $this->client
58
            ->request('GET', $ipAddress)
59
            ->getBody()
60
            ->getContents();
61
62
        /** @var array */
63
        return json_decode($responseJson, true);
64
    }
65
66
    /**
67
     * Defensive programming to not give ipstack.com an invalid language param.
68
     * If the .env or config file provided language code is not valid, return the default.
69
     * @return string
70
     */
71
    private function getLanguage() : string
72
    {
73
        /** @var string $defaultLanguage */
74
        $defaultLanguage = config('ipstack-finder.default_language');
75
76
        return (in_array($defaultLanguage, $this->supportedLanguages))
77
            ? $defaultLanguage : self::DEFAULT_LANGUAGE;
78
    }
79
}
80