-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiReader.php
226 lines (196 loc) · 6.6 KB
/
ApiReader.php
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
<?php
/**
* Copyright © Fastbolt Schraubengroßhandels GmbH.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Fastbolt\EntityImporter\Reader;
use Fastbolt\EntityImporter\EntityImporterDefinition;
use Fastbolt\EntityImporter\Reader\Api\PagePaginationStrategy;
use Fastbolt\EntityImporter\Reader\Api\PaginationStrategy;
use Fastbolt\EntityImporter\Types\ImportSourceDefinition\Api;
use Fastbolt\EntityImporter\Types\ImportSourceDefinition\ImportSourceDefinition;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Webmozart\Assert\Assert;
class ApiReader implements ReaderInterface
{
/**
* @var callable():Client
*/
private $clientFactory;
private EntityImporterDefinition $importerDefinition;
private ImportSourceDefinition|Api $importSourceDefinition;
private array $options;
/**
* @var array<int, array>
*/
private array $data = [];
private int $position = 0;
private bool $readToEnd = false;
/**
* @param EntityImporterDefinition $importerDefinition
* @param array $options
* @param callable():Client $clientFactory
*/
public function __construct(
EntityImporterDefinition $importerDefinition,
array $options,
callable $clientFactory
) {
$this->clientFactory = $clientFactory;
$this->importerDefinition = $importerDefinition;
$this->options = $options;
/** @var Api $apiTmp */
$apiTmp = $importerDefinition->getImportSourceDefinition();
$this->importSourceDefinition = $apiTmp;
Assert::keyExists($this->options, 'api_key');
if (!isset($this->options['pagination_strategy'])) {
$this->options['pagination_strategy'] = new PagePaginationStrategy(500);
}
if (!isset($this->options['serialized_format'])) {
$this->options['serialized_format'] = 'json';
}
}
/**
* Return the current element
*
* @return array
*/
public function current(): array
{
return $this->data[$this->position];
}
/**
* Move forward to next element
*/
public function next(): void
{
++$this->position;
}
/**
* Return the key of the current element
*/
public function key(): int
{
return $this->position;
}
/**
* Checks if current position is valid
*
* Returns true on success or false on failure.
*/
public function valid(): bool
{
if (isset($this->data[$this->position])) {
return true;
}
if ($this->readToEnd) {
return false;
}
$this->loadBulkData($this->position);
return isset($this->data[$this->position]);
}
/**
* @param int $offset
*
* @return void
*/
private function loadBulkData(int $offset): void
{
/** @var Api $importSourceDefinition */
$importSourceDefinition = $this->importSourceDefinition;
$clientFactory = $this->clientFactory;
$client = $clientFactory();
/** @var PaginationStrategy $paginationStrategy */
$paginationStrategy = $this->options['pagination_strategy'];
$paginationParameters = $paginationStrategy->getRequestParameters($offset);
$queryParameters = $importSourceDefinition->getQueryParameters();
$requestParameters = array_merge_recursive(
[
'verify' => false,
'headers' => [
'Accept' => 'application/json',
'X-AUTH-TOKEN' => (string) $importSourceDefinition->getOptions()['api_key'],
],
],
array_merge_recursive($queryParameters, $paginationParameters)
);
$url = $importSourceDefinition->getSource();
$requestMethod = Request::METHOD_GET;
try {
/** @var Response $response */
$response = $client->request(
$requestMethod,
$url,
$requestParameters
);
} catch (RequestException $exception) {
$response = $exception->getResponse();
throw new HttpException(
$response ? $response->getStatusCode() : 0,
sprintf(
'Connection error (%s request to %s returned %s (%s)) (%s).',
$requestMethod,
$url,
$response ? $response->getStatusCode() : 'null',
$response ? $response->getReasonPhrase() : 'empty response',
$exception->getMessage()
)
);
}
if ($response->getStatusCode() !== HttpResponse::HTTP_OK) {
throw new HttpException(
$response->getStatusCode(),
sprintf(
'Connection error (%s request to %s returned %s (%s)).',
$requestMethod,
$url,
$response->getStatusCode(),
$response->getReasonPhrase()
)
);
}
if (($body = $response->getBody()->getContents()) === '') {
throw new HttpException(
$response->getStatusCode(),
sprintf(
'Connection error (%s request to %s returned %s (%s), but resulted in empty data.).',
$requestMethod,
$url,
$response->getStatusCode(),
$response->getReasonPhrase()
)
);
}
$itemsPerPage = $paginationStrategy->getItemsPerPage();
$startOffset = $paginationStrategy->getPageStartOffset($offset);
/** @var array<int,mixed> $data */
$data = json_decode($body, true);
if (count($data) !== $itemsPerPage) {
$this->readToEnd = true;
}
foreach ($data as $dataOffset => $datum) {
$this->data[$dataOffset + $startOffset] = $datum;
}
$x = 1;
}
/**
* Rewind the Iterator to the first element
*/
public function rewind(): void
{
$this->position = 0;
}
/**
* @return array<int,array<int,mixed>>
*/
public function getErrors(): array
{
return [];
}
}