1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Speicher210\Estimote; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use GuzzleHttp\Exception\ClientException; |
9
|
|
|
use JMS\Serializer\SerializationContext; |
10
|
|
|
use JMS\Serializer\SerializerBuilder; |
11
|
|
|
use JMS\Serializer\SerializerInterface; |
12
|
|
|
use Speicher210\Estimote\Exception\ApiException; |
13
|
|
|
use Speicher210\Estimote\Exception\ApiKeyInvalidException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Abstract resource. |
17
|
|
|
*/ |
18
|
|
|
abstract class AbstractResource |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* The API client. |
22
|
|
|
* |
23
|
|
|
* @var Client |
24
|
|
|
*/ |
25
|
|
|
protected $client; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Serializer interface to serialize / deserialize the request / responses. |
29
|
|
|
* |
30
|
|
|
* @var SerializerInterface |
31
|
|
|
*/ |
32
|
|
|
protected $serializer; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param Client $client The API client. |
36
|
|
|
* @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses. |
37
|
|
|
*/ |
38
|
|
|
public function __construct(Client $client, SerializerInterface $serializer = null) |
39
|
|
|
{ |
40
|
|
|
$this->client = $client; |
41
|
|
|
$this->serializer = $serializer ?? $this->buildSerializer(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function buildSerializer(): SerializerInterface |
45
|
|
|
{ |
46
|
|
|
return SerializerBuilder::create() |
47
|
|
|
->setSerializationContextFactory( |
48
|
|
|
function () { |
49
|
|
|
return SerializationContext::create()->setSerializeNull(false); |
50
|
|
|
} |
51
|
|
|
) |
52
|
|
|
->build(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Create an ApiException from a client exception. |
57
|
|
|
* |
58
|
|
|
* @param ClientException $e The client exception. |
59
|
|
|
* @return ApiException |
60
|
|
|
*/ |
61
|
|
|
protected function createApiException(ClientException $e): ApiException |
62
|
|
|
{ |
63
|
|
|
$response = $e->getResponse(); |
64
|
|
|
|
65
|
|
|
if (\in_array($response->getStatusCode(), [401, 403], true)) { |
66
|
|
|
return new ApiKeyInvalidException(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return new ApiException((string)$response->getBody()); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|