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.

ApiKeyHelper   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
c 3
b 0
f 0
lcom 0
cbo 6
dl 0
loc 57
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getApiKey() 0 23 2
A apiKeyIsValid() 0 16 3
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Speicher210\KontaktIO;
6
7
use GuzzleHttp\Client as GuzzleHttpClient;
8
use GuzzleHttp\Exception\ClientException;
9
use Speicher210\KontaktIO\Exception\ApiKeyExtractionInvalidCredentialsException;
10
11
/**
12
 * Helper functions around the API key.
13
 */
14
class ApiKeyHelper
15
{
16
    /**
17
     * Get the API key using a username and password combination.
18
     *
19
     * @param string $username The username.
20
     * @param string $password The password.
21
     * @return string
22
     * @throws \Speicher210\KontaktIO\Exception\ApiKeyExtractionInvalidCredentialsException
23
     */
24
    public function getApiKey($username, $password)
25
    {
26
        $client = new GuzzleHttpClient(['cookies' => true, 'allow_redirects' => false]);
27
        $client->post(
28
            'https://panel.kontakt.io/signin',
29
            [
30
                'form_params' => [
31
                    'username' => $username,
32
                    'password' => $password
33
                ]
34
            ]
35
        );
36
37
        $response = $client->get('https://panel.kontakt.io/api-key');
38
39
        if ($response->getStatusCode() !== 200) {
40
            throw new ApiKeyExtractionInvalidCredentialsException();
41
        }
42
43
        $response = \json_decode($response->getBody()->getContents(), true);
44
45
        return $response['apiKey'];
46
    }
47
48
    /**
49
     * Check if an API key is valid.
50
     *
51
     * @param string $apiKey The API key to check.
52
     * @return bool
53
     */
54
    public function apiKeyIsValid(string $apiKey): bool
55
    {
56
        $client = new Client($apiKey);
57
58
        try {
59
            $client->get('/manager/me');
60
61
            return true;
62
        } catch (ClientException $e) {
63
            if ($e->getResponse()->getStatusCode() === 401) {
64
                return false;
65
            }
66
67
            throw $e;
68
        }
69
    }
70
}
71