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\InvalidResponseException; |
9
|
|
|
|
10
|
|
|
class AuthClient extends AbstractClient |
11
|
|
|
{ |
12
|
|
|
private $apiKey; |
13
|
|
|
private $apiToken = null; |
14
|
|
|
private $loginEndpoint; |
15
|
|
|
|
16
|
|
|
public function __construct(string $apiKey, string $loginEndpoint = null, HttpClient $httpClient = null, MessageFactory $messageFactory = null) |
17
|
|
|
{ |
18
|
|
|
parent::__construct($httpClient, $messageFactory); |
19
|
|
|
|
20
|
|
|
$this->apiKey = $apiKey; |
21
|
|
|
$this->loginEndpoint = $loginEndpoint ?? 'https://api.yproximite.fr/login_check'; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @throws InvalidApiKeyException |
26
|
|
|
* @throws AuthenticationException |
27
|
|
|
* @throws InvalidResponseException |
28
|
|
|
*/ |
29
|
|
|
public function auth() |
30
|
|
|
{ |
31
|
|
|
if ($this->isAuthenticated()) { |
32
|
|
|
return; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$request = $this->getMessageFactory()->createRequest('POST', $this->loginEndpoint, [], http_build_query(['api_key' => $this->apiKey])); |
36
|
|
|
$response = $this->getHttpClient()->sendRequest($request); |
37
|
|
|
$contents = json_decode((string) $response->getBody(), true); |
38
|
|
|
|
39
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
40
|
|
|
throw new InvalidResponseException('Could not decode response.', $request, $response); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ($response->getStatusCode() === 401) { |
44
|
|
|
throw new AuthenticationException('Your API key is not valid.', $request, $response); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->apiToken = $contents['token']; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function isAuthenticated(): bool |
51
|
|
|
{ |
52
|
|
|
return $this->apiToken !== null; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function getApiKey(): string |
56
|
|
|
{ |
57
|
|
|
return $this->apiKey; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getApiToken(): string |
61
|
|
|
{ |
62
|
|
|
return $this->apiToken; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|