Completed
Pull Request — master (#9)
by Hugo
01:41
created

AuthClient   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A auth() 0 15 2
A isAuthenticated() 0 4 1
A getApiKey() 0 4 1
A getApiToken() 0 4 1
A clearApiToken() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yproximite\Api\Client;
6
7
use Http\Client\HttpClient;
8
use Http\Message\MessageFactory;
9
use Yproximite\Api\Exception\AuthenticationException;
10
use Yproximite\Api\Exception\InvalidResponseException;
11
12
class AuthClient extends AbstractClient
13
{
14
    private $apiKey;
15
    private $apiToken = null;
16
    private $loginEndpoint;
17
18
    public function __construct(string $apiKey, string $loginEndpoint = null, HttpClient $httpClient = null, MessageFactory $messageFactory = null)
19
    {
20
        parent::__construct($httpClient, $messageFactory);
21
22
        $this->apiKey        = $apiKey;
23
        $this->loginEndpoint = $loginEndpoint ?? 'https://api.yproximite.fr/login_check';
24
    }
25
26
    /**
27
     * @throws AuthenticationException
28
     * @throws InvalidResponseException
29
     * @throws \Http\Client\Exception
30
     */
31
    public function auth(): void
32
    {
33
        if ($this->isAuthenticated()) {
34
            return;
35
        }
36
37
        $headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
38
        $body    = http_build_query(['api_key' => $this->apiKey]);
39
40
        $request  = $this->createRequest('POST', $this->loginEndpoint, $headers, $body);
41
        $response = $this->sendRequest($request);
42
        $json     = $this->extractJson($request, $response);
43
44
        $this->apiToken = $json['token'];
45
    }
46
47
    public function isAuthenticated(): bool
48
    {
49
        return null !== $this->apiToken;
50
    }
51
52
    public function getApiKey(): string
53
    {
54
        return $this->apiKey;
55
    }
56
57
    public function getApiToken(): ?string
58
    {
59
        return $this->apiToken;
60
    }
61
62
    public function clearApiToken(): void
63
    {
64
        $this->apiKey = null;
65
    }
66
}
67