GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 9aa323...8e0769 )
by Carsten
03:47 queued 10s
created

IpstackClient::decode()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 11
cts 11
cp 1
rs 9.2248
c 0
b 0
f 0
cc 5
nc 2
nop 1
crap 5
1
<?php
2
namespace Germania\IpstackClient;
3
4
use GuzzleHttp\ClientInterface;
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\GuzzleException;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
use Psr\Log\LoggerAwareTrait;
10
11
class IpstackClient implements IpstackClientInterface{
12
	
13
	use LoggerAwareTrait;
14
15
	/**
16
	 * @var ClientInterface
17
	 */
18
	public $guzzle_client;
19
20
	/**
21
	 * @var string
22
	 */
23
	public $http_method = "GET";
24
25
    /**
26
     * The ipstack API endpoint
27
     * @var string
28
     */
29
    public $ipstack_endpoint;
30
31
    /**
32
     * The ipstack API Key
33
     * @var string
34
     */
35
    public $ipstack_api_key;
36
37
38
39
    /**
40
     * @var array
41
     */
42
    public $ipstack_query_defaults = array(
43
        "output"     => "json",
44
        #"fields"     => "kkol,ip,country_code,country_name,latitude,longitude,region_name", #hostname
45
	);
46
47
48
    /**
49
     * @param string               $ipstack_endpoint
50
     * @param string               $ipstack_api_key
51
     * @param ClientInterface      $guzzle_client    Optional: Custom Guzzle Client
52
     * @param LoggerInterface|null $logger           Optional: PSR-3 Logger
53
     */
54 16
	public function __construct( string $ipstack_endpoint, string $ipstack_api_key, ClientInterface $guzzle_client = null, LoggerInterface $logger = null )
55
	{
56 16
		$this->ipstack_endpoint = $ipstack_endpoint;
57 16
		$this->ipstack_api_key  = $ipstack_api_key;
58
59 16
		$this->guzzle_client    = $guzzle_client ?: new Client;
60 16
		$this->setLogger( $logger ?: new NullLogger );
61
62 16
		$this->ipstack_query_defaults  = array_merge($this->ipstack_query_defaults, [
63 16
			"access_key" => $this->ipstack_api_key
64
		]);
65 16
	}
66
67
68
	/**
69
	 * @param  string $client_ip    [description]
70
	 * @param  array  $custom_query [description]
71
	 * @return array
72
	 *
73
	 * @throws IpstackExceptionInterface
74
	 */
75 16
	public function get( string $client_ip, array $custom_query = array() ) : array
76
	{
77 16
        $url = join("", [ $this->ipstack_endpoint, urlencode($client_ip) ]);
78 16
	    $query_params = array_merge($this->ipstack_query_defaults, $custom_query);
79
80
	    $logger_info = [
81 16
            'client_ip' => $client_ip,
82 16
            'method'    => $this->http_method,
83 16
            'endpoint'  => $this->ipstack_endpoint
84
        ];
85
86
    
87
    	// Request
88
	    try {
89 16
	    	$this->logger->debug("Requesting ipstack", $logger_info);
90 16
			$ipstack_response = $this->guzzle_client->request( 
91 16
				$this->http_method, 
92 12
				$url, 
93 16
				array('query' => $query_params)
94
			);		
95
	    } 
96 4
	    catch (GuzzleException $e) {
97 4
            $this->logger->error("GuzzleException", array_merge([
98 4
            	'exception' => get_class( $e ),
99 4
                'message'   => $e->getMessage()
100 3
            ], $logger_info));
101 4
            throw new IpstackRequestException("Request failed", 0, $e);
102
	    };
103
104
105
        // Evaluate response
106
        try {
107 12
	        $ipstack_response_body = $ipstack_response->getBody();
108 12
	        $ipstack = $this->decode( $ipstack_response_body );
109
        }
110 8
        catch (IpstackResponseException $e) {
111 8
            $this->logger->error("Ipstack ResponseException", array_merge([
112 8
                'message'   => $e->getMessage()
113 6
            ], $logger_info));
114 8
			throw $e;        	
115
        }
116
117 4
		return $ipstack;
118
119
	}
120
121
122
	/**
123
	 * @param  string $body Reponse body string
124
	 * @return array
125
	 *
126
	 * @throws IpstackResponseException
127
	 */
128 12
	public function decode( string $body ): array
129
	{
130
        // Evaluate response
131 12
        $ipstack = json_decode( $body, "as_array" );
132
133
134
        // Check for errors
135
        // https://ipstack.com/documentation#errors
136
137 12
        if ( array_key_exists("success", $ipstack) 
138 12
        and  $ipstack['success'] === false
139 12
    	and  array_key_exists("error", $ipstack)
140 12
    	and  is_array($ipstack['error'])):
141
142 8
    		$msg = sprintf("%s: %s", 
143 8
    			$ipstack['error']['type'] ?? 'Error',
144 8
    			$ipstack['error']['info'] ?? 'No description provided' );
145 8
			throw new IpstackResponseException($msg, $ipstack['error']['code'] ?? 0);
146
147
		endif;
148
149
150 4
		return $ipstack;
151
	} 
152
153
154
}