1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Speicher210\KontaktIO; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Exception\ClientException; |
8
|
|
|
use JMS\Serializer\SerializerBuilder; |
9
|
|
|
use JMS\Serializer\SerializerInterface; |
10
|
|
|
use Speicher210\KontaktIO\Exception\ApiException; |
11
|
|
|
use Speicher210\KontaktIO\Exception\ApiKeyInvalidException; |
12
|
|
|
use Speicher210\KontaktIO\Model\ApiErrorResponse; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Abstract resource. |
16
|
|
|
*/ |
17
|
|
|
class AbstractResource |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* The API client. |
21
|
|
|
* |
22
|
|
|
* @var Client |
23
|
|
|
*/ |
24
|
|
|
protected $client; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Serializer interface to serialize / deserialize the request / responses. |
28
|
|
|
* |
29
|
|
|
* @var SerializerInterface |
30
|
|
|
*/ |
31
|
|
|
protected $serializer; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Constructor. |
35
|
|
|
* |
36
|
|
|
* @param Client $client The API client. |
37
|
|
|
* @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses. |
38
|
|
|
*/ |
39
|
|
|
public function __construct(Client $client, SerializerInterface $serializer = null) |
40
|
|
|
{ |
41
|
|
|
$this->client = $client; |
42
|
|
|
$this->serializer = $serializer ?? $this->buildSerializer(); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function buildSerializer(): SerializerInterface |
46
|
|
|
{ |
47
|
|
|
return SerializerBuilder::create()->build(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Create an ApiException from a client exception. |
52
|
|
|
* |
53
|
|
|
* @param ClientException $e The client exception. |
54
|
|
|
* @return ApiException |
55
|
|
|
* @throws \Speicher210\KontaktIO\Exception\ApiKeyInvalidException |
56
|
|
|
*/ |
57
|
|
|
protected function createApiException(ClientException $e): ApiException |
58
|
|
|
{ |
59
|
|
|
$response = $e->getResponse(); |
60
|
|
|
|
61
|
|
|
if (\in_array($response->getStatusCode(), [401, 403], true)) { |
62
|
|
|
throw ApiKeyInvalidException::forResponse($response); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if ($response->getBody()->getSize() > 0) { |
66
|
|
|
/** @var ApiErrorResponse $apiErrorResponse */ |
67
|
|
|
$apiErrorResponse = $this->serializer->deserialize( |
68
|
|
|
$e->getResponse()->getBody(), |
69
|
|
|
ApiErrorResponse::class, |
70
|
|
|
'json' |
71
|
|
|
); |
72
|
|
|
} else { |
73
|
|
|
$apiErrorResponse = new ApiErrorResponse(); |
74
|
|
|
$apiErrorResponse->setStatus($response->getStatusCode()); |
75
|
|
|
$apiErrorResponse->setMessage($response->getReasonPhrase()); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return new ApiException($apiErrorResponse, $e); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: