Completed
Pull Request — master (#9)
by Hugo
02:11
created

AuthClient   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 8
dl 0
loc 49
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B auth() 0 24 5
A isAuthenticated() 0 4 1
1
<?php
2
3
namespace Yproximite\Api\Client;
4
5
use Http\Client\HttpClient;
6
use Http\Message\MessageFactory;
7
use Yproximite\Api\Exception\AuthenticationException;
8
use Yproximite\Api\Exception\InvalidApiKeyException;
9
use Yproximite\Api\Exception\InvalidResponseException;
10
11
class AuthClient extends AbstractClient
12
{
13
    private $apiKey;
14
    private $apiToken;
15
    private $loginEndpoint;
16
17
    public function __construct(string $apiKey, string $loginEndpoint = null, HttpClient $httpClient = null, MessageFactory $messageFactory = null)
18
    {
19
        parent::__construct($httpClient, $messageFactory);
20
21
        $this->apiKey        = $apiKey;
22
        $this->loginEndpoint = $loginEndpoint ?? 'https://api.yproximite.fr/login_check';
23
    }
24
25
    /**
26
     * @throws InvalidApiKeyException
27
     * @throws AuthenticationException
28
     * @throws InvalidResponseException
29
     */
30
    public function auth()
31
    {
32
        if ($this->isAuthenticated()) {
33
            return;
34
        }
35
36
        if (null === $this->apiKey) {
37
            throw new InvalidApiKeyException('API key can not be empty. Specify it during object initialization or call « setApiKey » method.');
38
        }
39
40
        $request  = $this->getMessageFactory()->createRequest('POST', $this->loginEndpoint, ['api_key' => $this->apiKey]);
41
        $response = $this->getHttpClient()->sendRequest($request);
42
        $contents = json_decode($response->getBody()->getContents(), true);
43
44
        if (json_last_error() !== JSON_ERROR_NONE) {
45
            throw new InvalidResponseException('Could not decode response.', $request, $response);
46
        }
47
48
        if ($response->getStatusCode() === 401) {
49
            throw new AuthenticationException('Your API key is not valid.', $request, $response);
50
        }
51
52
        $this->apiToken = $contents['token'];
53
    }
54
55
    public function isAuthenticated(): bool
56
    {
57
        return $this->apiToken !== null;
58
    }
59
}
60