|
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
|
|
|
|