-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractSyncProvider.php
More file actions
322 lines (290 loc) · 9.24 KB
/
Copy pathAbstractSyncProvider.php
File metadata and controls
322 lines (290 loc) · 9.24 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
<?php declare(strict_types=1);
namespace Salient\Sync;
use Salient\Contract\Container\ContainerInterface;
use Salient\Contract\Container\HasContextualBindings;
use Salient\Contract\Container\HasServices;
use Salient\Contract\Core\Pipeline\PipelineInterface;
use Salient\Contract\Sync\FilterPolicy;
use Salient\Contract\Sync\SyncContextInterface;
use Salient\Contract\Sync\SyncEntityInterface;
use Salient\Contract\Sync\SyncProviderInterface;
use Salient\Contract\Sync\SyncStoreInterface;
use Salient\Core\Provider\AbstractProvider;
use Salient\Core\Pipeline;
use Salient\Sync\Exception\FilterPolicyViolationException;
use Salient\Sync\Exception\SyncEntityRecursionException;
use Salient\Sync\Reflection\SyncProviderReflection;
use Salient\Sync\Support\SyncContext;
use Salient\Sync\Support\SyncEntityProvider;
use Salient\Sync\Support\SyncIntrospector;
use Salient\Sync\Support\SyncPipelineArgument;
use Salient\Utility\Regex;
use Salient\Utility\Str;
use Closure;
use LogicException;
/**
* Base class for providers that sync entities to and from third-party backends
*/
abstract class AbstractSyncProvider extends AbstractProvider implements
SyncProviderInterface,
HasServices,
HasContextualBindings
{
/**
* Get a dependency substitution map for the provider
*
* {@inheritDoc}
*
* Override this method to bind any {@see SyncEntityInterface} classes
* customised for the provider to their generic parent classes, e.g.:
*
* ```php
* <?php
* public static function getContextualBindings(): array
* {
* return [
* Post::class => CustomPost::class,
* User::class => CustomUser::class,
* ];
* }
* ```
*/
public static function getContextualBindings(ContainerInterface $container): array
{
return [];
}
protected SyncStoreInterface $Store;
private int $Id;
/** @var array<string,Closure|null> */
private array $MagicMethodClosures = [];
/**
* Creates a new sync provider object
*
* Creating an instance of the provider registers it with the entity store
* injected by the container.
*/
public function __construct(ContainerInterface $app, SyncStoreInterface $store)
{
parent::__construct($app);
$this->Store = $store;
$this->Store->registerProvider($this);
}
/**
* @inheritDoc
*/
public function getContext(): SyncContextInterface
{
return new SyncContext($this, $this->App);
}
/**
* @inheritDoc
*/
public function getFilterPolicy(): ?int
{
return null;
}
/**
* @inheritDoc
*/
public function isValidIdentifier($id, string $entity): bool
{
return is_int($id)
|| Regex::match(Regex::delimit('^' . Regex::MONGODB_OBJECTID . '$', '/'), $id)
|| Regex::match(Regex::delimit('^' . Regex::UUID . '$', '/'), $id);
}
/**
* @inheritDoc
*/
final public function getStore(): SyncStoreInterface
{
return $this->Store;
}
/**
* @inheritDoc
*/
final public function getProviderId(): int
{
return $this->Id ??= $this->Store->getProviderId($this);
}
/**
* Perform a sync operation if its context is valid
*
* Providers where sync operations are performed by declared methods should
* use this method to ensure filter policy violations are caught and to take
* advantage of other safety checks that may be added in the future.
*
* Example:
*
* ```php
* <?php
* class Provider extends HttpSyncProvider
* {
* public function getEntities(SyncContextInterface $ctx): iterable
* {
* // Claim filter values
* $start = $ctx->claimFilter('start_date');
* $end = $ctx->claimFilter('end_date');
*
* return $this->run(
* $ctx,
* fn(): iterable =>
* Entity::provide(
* $this->getCurler('/entities')->getP([
* 'from' => $start,
* 'to' => $end,
* ]),
* $ctx,
* )
* );
* }
* }
* ```
*
* @template T of SyncEntityInterface
* @template TOutput of iterable<T>|T
*
* @param Closure(): TOutput $operation
* @return TOutput
*/
protected function run(SyncContextInterface $context, Closure $operation)
{
return $this->filterOperationOutput(
$context,
$this->runOperation($context, $operation),
);
}
/**
* Get a new pipeline for mapping provider data to entities
*
* @template T of SyncEntityInterface
*
* @param class-string<T> $entity
* @return PipelineInterface<mixed[],T,SyncPipelineArgument>
*/
protected function pipelineFrom(string $entity): PipelineInterface
{
/** @var PipelineInterface<mixed[],T,SyncPipelineArgument> */
return Pipeline::create();
}
/**
* Get a new pipeline for mapping entities to provider data
*
* @template T of SyncEntityInterface
*
* @param class-string<T> $entity
* @return PipelineInterface<T,mixed[],SyncPipelineArgument>
*/
protected function pipelineTo(string $entity): PipelineInterface
{
/** @var PipelineInterface<T,mixed[],SyncPipelineArgument> */
return Pipeline::create();
}
/**
* @inheritDoc
*/
final public static function getServices(): array
{
$provider = new SyncProviderReflection(static::class);
return $provider->getSyncProviderInterfaces();
}
/**
* @template TEntity of SyncEntityInterface
*
* @param class-string<TEntity> $entity
* @return SyncEntityProvider<TEntity,static>
*/
final public function with(string $entity, ?SyncContextInterface $context = null): SyncEntityProvider
{
if ($context) {
if ($context->recursionDetected()) {
throw new SyncEntityRecursionException(sprintf(
'Circular reference detected: %s',
$context->getLastEntity()->getUri($this->Store),
));
}
$container = $context->getContainer();
} else {
$container = $this->App;
}
$container = $container->inContextOf(static::class);
$context = ($context ?? $this->getContext())->withContainer($container);
return $container->get(
SyncEntityProvider::class,
['entity' => $entity, 'provider' => $this, 'context' => $context],
);
}
/**
* @template T
* @template TOutput of iterable<T>|T
*
* @param Closure(): TOutput $operation
* @return TOutput
*/
final public function runOperation(SyncContextInterface $context, Closure $operation)
{
if (!$context->hasOperation()) {
throw new LogicException('Context has no operation');
}
if ($context->hasFilter()) {
$policy = $context->getProvider()->getFilterPolicy()
?? FilterPolicy::THROW_EXCEPTION;
switch ($policy) {
case FilterPolicy::IGNORE:
break;
case FilterPolicy::THROW_EXCEPTION:
throw new FilterPolicyViolationException(
$this,
$context->getEntityType(),
$context->getFilters(),
);
case FilterPolicy::RETURN_EMPTY:
/** @var TOutput */
return SyncUtil::isListOperation($context->getOperation())
? []
: null;
case FilterPolicy::FILTER:
break;
default:
throw new LogicException(sprintf(
'Invalid unclaimed filter policy: %d',
$policy,
));
}
}
return $operation();
}
/**
* @inheritDoc
*/
final public function filterOperationOutput(SyncContextInterface $context, $output)
{
if (!$context->hasOperation()) {
throw new LogicException('Context has no operation');
}
if (
$context->hasFilter()
&& $context->getProvider()->getFilterPolicy() === FilterPolicy::FILTER
) {
throw new LogicException('Unclaimed filter policy not implemented');
}
return $output;
}
/**
* @param mixed[] $arguments
* @return mixed
*/
final public function __call(string $name, array $arguments)
{
$name = Str::lower($name);
if (array_key_exists($name, $this->MagicMethodClosures)) {
$closure = $this->MagicMethodClosures[$name];
} else {
$closure = SyncIntrospector::get(static::class)->getMagicSyncOperationClosure($name, $this);
$this->MagicMethodClosures[$name] = $closure;
}
if ($closure) {
return $closure(...$arguments);
}
throw new LogicException('Call to undefined method: ' . static::class . "::$name()");
}
}