-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathPorter.php
More file actions
349 lines (296 loc) · 10.4 KB
/
Porter.php
File metadata and controls
349 lines (296 loc) · 10.4 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
namespace ScriptFUSION\Porter;
use DeepCopy\DeepCopy;
use DeepCopy\Filter\KeepFilter;
use DeepCopy\Matcher\PropertyTypeMatcher;
use DeepCopy\TypeFilter\ShallowCopyFilter;
use DeepCopy\TypeMatcher\TypeMatcher;
use Eloquent\Enumeration\MultitonInterface;
use Mockery\MockInterface;
use ScriptFUSION\Porter\Cache\CacheAdvice;
use ScriptFUSION\Porter\Cache\CacheToggle;
use ScriptFUSION\Porter\Cache\CacheUnavailableException;
use ScriptFUSION\Porter\Collection\CountablePorterRecords;
use ScriptFUSION\Porter\Collection\CountableProviderRecords;
use ScriptFUSION\Porter\Collection\PorterRecords;
use ScriptFUSION\Porter\Collection\ProviderRecords;
use ScriptFUSION\Porter\Collection\RecordCollection;
use ScriptFUSION\Porter\Connector\RecoverableConnectorException;
use ScriptFUSION\Porter\Provider\ObjectNotCreatedException;
use ScriptFUSION\Porter\Provider\Provider;
use ScriptFUSION\Porter\Provider\ProviderFactory;
use ScriptFUSION\Porter\Provider\Resource\ProviderResource;
use ScriptFUSION\Porter\Specification\ImportSpecification;
use ScriptFUSION\Porter\Transform\Transformer;
use ScriptFUSION\Retry\ExceptionHandler\ExponentialBackoffExceptionHandler;
/**
* Imports data according to an ImportSpecification.
*/
class Porter
{
const DEFAULT_FETCH_ATTEMPTS = 5;
/**
* @var Provider[]
*/
private $providers;
/**
* @var ProviderFactory
*/
private $providerFactory;
/**
* @var CacheAdvice
*/
private $defaultCacheAdvice;
/**
* @var int
*/
private $maxFetchAttempts = self::DEFAULT_FETCH_ATTEMPTS;
/**
* @var DeepCopy
*/
private $deepCopy;
/**
* @var callable
*/
private $fetchExceptionHandler;
public function __construct()
{
$this->defaultCacheAdvice = CacheAdvice::SHOULD_NOT_CACHE();
$this->deepCopy = $this->createDeepCopier();
}
/**
* Imports data according to the design of the specified import specification.
*
* @param ImportSpecification $specification Import specification.
*
* @return PorterRecords
*
* @throws ImportException Provider failed to return an iterator.
*/
public function import(ImportSpecification $specification)
{
/** @var ImportSpecification $specification */
$specification = $this->deepCopy->copy($specification);
$records = $this->fetch($specification->getResource(), $specification->getCacheAdvice());
if (!$records instanceof ProviderRecords) {
$records = $this->createProviderRecords($records, $specification->getResource());
}
$records = $this->transformRecords($records, $specification->getTransformers(), $specification->getContext());
return $this->createPorterRecords($records, $specification);
}
/**
* Imports one record according to the design of the specified import specification.
*
* @param ImportSpecification $specification Import specification.
*
* @return array|null Record.
*
* @throws ImportException More than one record was imported.
*/
public function importOne(ImportSpecification $specification)
{
$results = $this->import($specification);
if (!$results->valid()) {
return null;
}
$one = $results->current();
if ($results->next() || $results->valid()) {
throw new ImportException('Cannot import one: more than one record imported.');
}
return $one;
}
private function fetch(ProviderResource $resource, CacheAdvice $cacheAdvice = null)
{
$provider = $this->getProvider($resource->getProviderClassName(), $resource->getProviderTag());
$this->applyCacheAdvice($provider, $cacheAdvice ?: $this->defaultCacheAdvice);
if (($records = \ScriptFUSION\Retry\retry(
$this->getMaxFetchAttempts(),
function () use ($provider, $resource) {
return $provider->fetch($resource);
},
function (\Exception $exception) {
// Throw exception if unrecoverable.
if (!$exception instanceof RecoverableConnectorException) {
throw $exception;
}
call_user_func($this->getFetchExceptionHandler(), $exception);
}
)) instanceof \Iterator) {
return $records;
}
throw new ImportException(get_class($provider) . '::fetch() did not return an Iterator.');
}
/**
* @param RecordCollection $records
* @param Transformer[] $transformers
* @param mixed $context
*
* @return RecordCollection
*/
private function transformRecords(RecordCollection $records, array $transformers, $context)
{
foreach ($transformers as $transformer) {
if ($transformer instanceof PorterAware) {
$transformer->setPorter($this);
}
$records = $transformer->transform($records, $context);
}
return $records;
}
private function createProviderRecords(\Iterator $records, ProviderResource $resource)
{
if ($records instanceof \Countable) {
return new CountableProviderRecords($records, count($records), $resource);
}
return new ProviderRecords($records, $resource);
}
private function createPorterRecords(RecordCollection $records, ImportSpecification $specification)
{
if ($records instanceof \Countable) {
return new CountablePorterRecords($records, count($records), $specification);
}
return new PorterRecords($records, $specification);
}
private function applyCacheAdvice(Provider $provider, CacheAdvice $cacheAdvice)
{
try {
if (!$provider instanceof CacheToggle) {
throw CacheUnavailableException::modify();
}
switch ("$cacheAdvice") {
case CacheAdvice::MUST_CACHE:
case CacheAdvice::SHOULD_CACHE:
$provider->enableCache();
break;
case CacheAdvice::MUST_NOT_CACHE:
case CacheAdvice::SHOULD_NOT_CACHE:
$provider->disableCache();
}
} catch (CacheUnavailableException $exception) {
if ($cacheAdvice === CacheAdvice::MUST_NOT_CACHE() ||
$cacheAdvice === CacheAdvice::MUST_CACHE()
) {
throw $exception;
}
}
}
/**
* Registers the specified provider optionally identified by the specified tag.
*
* @param Provider $provider Provider.
* @param string|null $tag Optional. Provider tag.
*
* @return $this
*
* @throws ProviderAlreadyRegisteredException The specified provider is already registered.
*/
public function registerProvider(Provider $provider, $tag = null)
{
if ($this->hasProvider($name = get_class($provider), $tag)) {
throw new ProviderAlreadyRegisteredException("Provider already registered: \"$name\" with tag \"$tag\".");
}
$this->providers[$this->hashProviderName($name, $tag)] = $provider;
return $this;
}
/**
* Gets the provider matching the specified class name and optionally a tag.
*
* @param string $name Provider class name.
* @param string|null $tag Optional. Provider tag.
*
* @return Provider
*
* @throws ProviderNotFoundException The specified provider was not found.
*/
public function getProvider($name, $tag = null)
{
if ($this->hasProvider($name, $tag)) {
return $this->providers[$this->hashProviderName($name, $tag)];
}
try {
// Tags are not supported for lazy-loaded providers because every instance would be the same.
if ($tag === null) {
$this->registerProvider($provider = $this->getOrCreateProviderFactory()->createProvider("$name"));
return $provider;
}
} catch (ObjectNotCreatedException $exception) {
// We will throw our own exception.
}
throw new ProviderNotFoundException(
"No such provider registered: \"$name\" with tag \"$tag\".",
isset($exception) ? $exception : null
);
}
/**
* Gets a value indicating whether the specified provider is registered.
*
* @param string $name Provider class name.
* @param string|null $tag Optional. Provider tag.
*
* @return bool True if the specified provider is registered, otherwise false.
*/
public function hasProvider($name, $tag = null)
{
return isset($this->providers[$this->hashProviderName($name, $tag)]);
}
/**
* @param string $name Provider class name.
* @param string|null $tag Provider tag.
*
* @return string Provider identifier hash.
*/
private function hashProviderName($name, $tag)
{
return "$name#$tag";
}
private function getOrCreateProviderFactory()
{
return $this->providerFactory ?: $this->providerFactory = new ProviderFactory;
}
/**
* Gets the maximum number of fetch attempts per import.
*
* @return int
*/
public function getMaxFetchAttempts()
{
return $this->maxFetchAttempts;
}
/**
* Sets the maximum number of fetch attempts per import.
*
* @param int $attempts Maximum fetch attempts.
*
* @return $this
*/
public function setMaxFetchAttempts($attempts)
{
$this->maxFetchAttempts = max(1, $attempts|0);
return $this;
}
/**
* @return callable
*/
private function getFetchExceptionHandler()
{
return $this->fetchExceptionHandler ?: $this->fetchExceptionHandler = new ExponentialBackoffExceptionHandler;
}
/**
* @param callable $fetchExceptionHandler
*/
public function setFetchExceptionHandler(callable $fetchExceptionHandler)
{
$this->fetchExceptionHandler = $fetchExceptionHandler;
}
/**
* @return DeepCopy
*/
private function createDeepCopier()
{
$copier = new DeepCopy;
// Enumerations are immutable thus do not require cloning.
$copier->addFilter(new KeepFilter, new PropertyTypeMatcher(MultitonInterface::class));
$copier->addTypeFilter(new ShallowCopyFilter, new TypeMatcher(MockInterface::class));
return $copier;
}
}