1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace LauLamanApps\IzettleApi; |
6
|
|
|
|
7
|
|
|
use DateTime; |
8
|
|
|
use GuzzleHttp\ClientInterface; |
9
|
|
|
use LauLamanApps\IzettleApi\Client\AccessToken; |
10
|
|
|
use LauLamanApps\IzettleApi\Client\Exceptions\AccessTokenExpiredException; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Ramsey\Uuid\UuidInterface; |
13
|
|
|
|
14
|
|
|
abstract class AbstractClient |
15
|
|
|
{ |
16
|
|
|
private $guzzleClient; |
17
|
|
|
private $accessToken; |
18
|
|
|
private $organizationUuid = 'self'; |
19
|
|
|
|
20
|
15 |
|
public function __construct(ClientInterface $guzzleClient, AccessToken $accessToken) |
21
|
|
|
{ |
22
|
15 |
|
$this->guzzleClient = $guzzleClient; |
23
|
15 |
|
$this->accessToken = $accessToken; |
24
|
15 |
|
$this->validateAccessToken(); |
25
|
13 |
|
} |
26
|
|
|
|
27
|
2 |
|
public function setOrganizationUuid(UuidInterface $organizationUuid): void |
28
|
|
|
{ |
29
|
2 |
|
$this->organizationUuid = (string) $organizationUuid; |
30
|
2 |
|
} |
31
|
|
|
|
32
|
9 |
|
protected function getOrganizationUuid(): string |
33
|
|
|
{ |
34
|
9 |
|
return $this->organizationUuid; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
|
38
|
6 |
|
protected function get(string $url, ?array $queryParameters = null): ResponseInterface |
39
|
|
|
{ |
40
|
6 |
|
$options = array_merge(['headers' => $this->getAuthorizationHeader()], ['query' => $queryParameters]); |
41
|
|
|
|
42
|
6 |
|
return $this->guzzleClient->get($url, $options); |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
protected function post(string $url, string $data): void |
46
|
|
|
{ |
47
|
3 |
|
$headers = array_merge( |
48
|
3 |
|
$this->getAuthorizationHeader(), |
49
|
|
|
[ |
50
|
3 |
|
'content-type' => 'application/json', |
51
|
|
|
'Accept' => 'application/json', |
52
|
|
|
] |
53
|
|
|
); |
54
|
|
|
|
55
|
3 |
|
$options = array_merge(['headers' => $headers], ['body' => $data]); |
56
|
|
|
|
57
|
3 |
|
$this->guzzleClient->post($url, $options); |
58
|
3 |
|
} |
59
|
|
|
|
60
|
2 |
|
protected function delete(string $url): void |
61
|
|
|
{ |
62
|
2 |
|
$this->guzzleClient->delete($url, ['headers' => $this->getAuthorizationHeader()]); |
63
|
2 |
|
} |
64
|
|
|
|
65
|
11 |
|
protected function getAuthorizationHeader(): array |
66
|
|
|
{ |
67
|
11 |
|
$this->validateAccessToken(); |
68
|
|
|
|
69
|
11 |
|
return ['Authorization' => sprintf('Bearer %s', $this->accessToken->getToken())]; |
70
|
|
|
} |
71
|
|
|
|
72
|
15 |
|
private function validateAccessToken(): void |
73
|
|
|
{ |
74
|
15 |
|
if ($this->accessToken->isExpired()) { |
75
|
2 |
|
throw new AccessTokenExpiredException( |
76
|
2 |
|
sprintf( |
77
|
2 |
|
'Access Token was valid till \'%s\' it\'s now \'%s\'', |
78
|
2 |
|
$this->accessToken->getExpires()->format('Y-m-d H:i:s.u'), |
79
|
2 |
|
(new DateTime())->format('Y-m-d H:i:s.u') |
80
|
|
|
) |
81
|
|
|
); |
82
|
|
|
} |
83
|
13 |
|
} |
84
|
|
|
} |
85
|
|
|
|