-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
293 lines (247 loc) · 7.99 KB
/
Client.php
File metadata and controls
293 lines (247 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
/*
* This file is part of datamolino client.
*
* (c) 2018 cwd.at GmbH <office@cwd.at>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Cwd\Datamolino;
use Cwd\Datamolino\Model\Token;
use GuzzleHttp\Psr7\Request;
use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use GuzzleHttp\Client as GuzzleClient;
class Client
{
private $apiUrl = 'https://beta.datamolino.com';
private $apiVersion = 'v1_2';
private $apiUri;
private $tokenUrl;
/** @var Token */
private $token;
/** @var HttpClient */
private $client;
/** @var Serializer */
private $serializer;
public function __construct(?GuzzleClient $client = null)
{
if (null === $client) {
$this->client = HttpClientDiscovery::find();
}
$this->setUris();
$normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter(), null, new ReflectionExtractor());
$this->serializer = new Serializer([new DateTimeNormalizer(), $normalizer], ['json' => new JsonEncoder()]);
}
/**
* @param string|null $payload
* @param int|string|null $id
* @param string $endpoint
* @param string|null $hydrationClass
* @param bool $isList
* @param string $method
* @param string|null $urlExtension - Special case only needed when retrieving original file!
*
* @throws \Http\Client\Exception
* @throws \LogicException
*
* @return mixed
*/
public function call($payload = null, $id = null, $endpoint = '', $hydrationClass = null, $isList = false, $method = 'POST', $urlExtension = null)
{
if (!$this->token instanceof Token) {
throw new \LogicException('Token not set - Authenticate first - or store refresh token for later use');
}
if (in_array($method, ['GET', 'PUT', 'DELETE'])) {
$format = (is_int($id)) ? '%s%s/%s' : '%s%s%s';
$uri = sprintf($format, $this->apiUri, $endpoint, $id);
} else {
$uri = (null !== $id) ? sprintf('%s%s/%s', $this->apiUri, $endpoint, $id) : $this->apiUri.$endpoint;
}
/* Special case only needed for retrieve original file */
if (null !== $urlExtension) {
$uri .= $urlExtension;
}
$request = new Request($method, $uri, [
'Authorization' => sprintf('Bearer %s', $this->token->getAccessToken()),
'Content-Type' => 'application/json',
], $payload);
$response = $this->client->sendRequest($request);
$responseBody = $response->getBody()->getContents();
$responseData = json_decode($responseBody);
if ($response->getStatusCode() >= 300) {
$message = isset($responseData->message) ?? 'Unknown';
throw new \Exception(sprintf('Error on request %s: %s', $response->getStatusCode(), $message));
}
if (null !== $hydrationClass && class_exists($hydrationClass) && isset($responseData->$endpoint)) {
return $this->denormalizeObject($hydrationClass, $responseData->$endpoint, $isList);
} elseif (null !== $hydrationClass && !class_exists($hydrationClass)) {
throw new \Exception(sprintf('HydrationClass (%s) does not exist', $hydrationClass));
} elseif (null !== $hydrationClass && !isset($responseData->$endpoint)) {
throw new \Exception(sprintf('Datapoint (%s) does not exist', $endpoint));
}
return $responseData;
}
/**
* @param string $clientId
* @param string $clientSecret
* @param string $username
* @param string $password
*
* @throws \Http\Client\Exception
*
* @return Token
*/
public function authenticatePassword($clientId, string $clientSecret, string $username, string $password): Token
{
$request = new Request('POST', $this->tokenUrl, [
'Content-Type' => 'application/json',
], json_encode([
'client_id' => $clientId,
'client_secret' => $clientSecret,
'username' => $username,
'password' => $password,
'grant_type' => 'password',
]));
$response = $this->getClient()->sendRequest($request);
$responseBody = $response->getBody()->getContents();
$this->token = $this->denormalizeObject(Token::class, [json_decode($responseBody)], false);
return $this->token;
}
/**
* @param string $clientId
* @param string $clientSecret
* @param string $refreshToken
*
* @throws \Http\Client\Exception
*
* @return Token
*/
public function refreshToken($clientId, $clientSecret, $refreshToken): Token
{
$request = new Request('POST', $this->tokenUrl, [
'Content-Type' => 'application/json',
], json_encode([
'client_id' => $clientId,
'client_secret' => $clientSecret,
'refresh_token' => $refreshToken,
'grant_type' => 'refresh_token',
]));
$response = $this->getClient()->sendRequest($request);
$responseBody = $response->getBody()->getContents();
$this->token = $this->denormalizeObject(Token::class, [json_decode($responseBody)], false);
return $this->token;
}
public function setToken(Token $token): Client
{
$this->token = $token;
return $this;
}
/**
* @return string
*/
public function getApiUrl(): string
{
return $this->apiUrl;
}
/**
* @param string $apiUrl
*
* @return Client
*/
public function setApiUrl(string $apiUrl): Client
{
$this->apiUrl = $apiUrl;
$this->setUris();
return $this;
}
/**
* @return string
*/
public function getApiVersion(): string
{
return $this->apiVersion;
}
/**
* @param string $apiVersion
*
* @return Client
*/
public function setApiVersion(string $apiVersion): Client
{
$this->apiVersion = $apiVersion;
return $this;
}
/**
* @return string
*/
public function getApiUri(): string
{
return $this->apiUri;
}
/**
* @param string $apiUri
*
* @return Client
*/
public function setApiUri(string $apiUri): Client
{
$this->apiUri = $apiUri;
$this->setUris();
return $this;
}
/**
* @return string
*/
public function getTokenUrl(): string
{
return $this->tokenUrl;
}
/**
* @param string $tokenUrl
*
* @return Client
*/
public function setTokenUrl(string $tokenUrl): Client
{
$this->tokenUrl = $tokenUrl;
return $this;
}
public function denormalizeObject($hydrationClass, $dataObject, $isList = false)
{
$result = [];
foreach ($dataObject as $data) {
$result[] = $this->serializer->denormalize($data, $hydrationClass, null, [
ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true,
]);
}
if ($isList) {
return $result;
}
return current($result);
}
protected function getClient(): HttpClient
{
return $this->client;
}
/**
* @return Serializer
*/
public function getSerializer(): Serializer
{
return $this->serializer;
}
private function setUris(): void
{
$this->apiUri = sprintf('%s/api/%s/', $this->apiUrl, $this->apiVersion);
$this->tokenUrl = $this->apiUrl.'/oauth/token';
}
}