-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWriteCommandExtractorDecorator.php
More file actions
349 lines (272 loc) · 10.9 KB
/
WriteCommandExtractorDecorator.php
File metadata and controls
349 lines (272 loc) · 10.9 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
declare(strict_types=1);
namespace Swh\SmartRelationSync\DataAbstractionLayer;
use RuntimeException;
use Shopware\Core\Framework\DataAbstractionLayer\CompiledFieldCollection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Field;
use Shopware\Core\Framework\DataAbstractionLayer\Field\FkField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Extension;
use Shopware\Core\Framework\DataAbstractionLayer\Field\ManyToManyAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\ManyToOneAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToManyAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\ReferenceVersionField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\VersionField;
use Shopware\Core\Framework\DataAbstractionLayer\Version\VersionDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Write\WriteCommandExtractor;
use Shopware\Core\Framework\DataAbstractionLayer\Write\WriteParameterBag;
use Swh\SmartRelationSync\ValueObject\RelevantField;
final class WriteCommandExtractorDecorator extends WriteCommandExtractor
{
/** @noinspection PhpMissingParentConstructorInspection */
public function __construct(
private readonly CleanupRelationsRegistry $cleanupRelationsRegistry,
private readonly WriteCommandExtractor $decorated,
) {}
public static function getCleanupEnableFieldName(Field $field): string
{
return sprintf('%sCleanupRelations', $field->getPropertyName());
}
/**
* @param array<mixed, mixed> $rawData
*/
public function extract(array $rawData, WriteParameterBag $parameters): array
{
$this->registerRelations($rawData, $parameters);
return $this->decorated->extract($rawData, $parameters);
}
/**
* @param non-empty-array<non-empty-string, non-empty-string> $parentPrimaryKey
*/
private function buildCleanupDataForManyToManyAssociation(
ManyToManyAssociationField $field,
array $parentPrimaryKey,
): CleanupRelationData {
$reference = $field->getReferenceDefinition();
$mappingAssociation = $this->getMappingAssociation($reference, $field);
$storageName = $mappingAssociation->getStorageName();
$fkPropertyName = $this->getForeignKeyPropertyNameByStorageName($reference->getFields(), $storageName);
$referencedDefinition = $field->getMappingDefinition();
$primaryKeyFields = $this->getPrimaryKeyFields($referencedDefinition);
unset($primaryKeyFields[$fkPropertyName]);
return new CleanupRelationData(
$reference,
$parentPrimaryKey,
$primaryKeyFields,
[$fkPropertyName => true],
);
}
/**
* @param non-empty-array<non-empty-string, non-empty-string> $parentPrimaryKey
*/
private function buildCleanupDataForOneToManyAssociation(
OneToManyAssociationField $field,
array $parentPrimaryKey,
): CleanupRelationData {
$reference = $field->getReferenceDefinition();
$fkPropertyName = $this->getForeignKeyPropertyNameByStorageName(
$reference->getFields(),
$field->getReferenceField(),
);
return new CleanupRelationData(
$reference,
$parentPrimaryKey,
[$fkPropertyName => true],
$this->getPrimaryKeyFields($reference),
);
}
/**
* @param non-empty-array<non-empty-string, non-empty-string> $primaryKeys
*
* @return non-empty-array<non-empty-string, non-empty-string>
*/
private function filterVersionFields(array $primaryKeys, EntityDefinition $definition): array
{
/** @var array<int, string> $versionFields */
$versionFields = $definition->getFields()
->filter(
static fn(Field $field) => $field instanceof ReferenceVersionField || $field instanceof VersionField,
)
->map(static fn(Field $field): string => $field->getPropertyName());
if ($versionFields === []) {
return $primaryKeys;
}
$primaryKeysWithoutVersionFields = array_diff_key($primaryKeys, array_flip($versionFields));
assert(
count($primaryKeysWithoutVersionFields) > 0,
'No primary keys remained after removing the version fields.',
);
return $primaryKeysWithoutVersionFields;
}
/**
* @return non-empty-string
*/
private function getForeignKeyPropertyNameByStorageName(
CompiledFieldCollection $fields,
string $storageName,
) {
$fk = $fields->getByStorageName($storageName);
assert(
$fk !== null,
'Could not find foreign key field by storage name ' . $storageName,
);
$fkPropertyName = $fk->getPropertyName();
assert($fkPropertyName !== '', 'Foreign key property name was empty');
return $fkPropertyName;
}
private function getMappingAssociation(
EntityDefinition $referencedDefinition,
ManyToManyAssociationField $field,
): ManyToOneAssociationField {
$associations = $referencedDefinition->getFields()->filterInstance(ManyToOneAssociationField::class);
foreach ($associations as $association) {
assert($association instanceof ManyToOneAssociationField);
if ($association->getStorageName() === $field->getMappingReferenceColumn()) {
return $association;
}
}
throw new RuntimeException('Association not found!'); // @codeCoverageIgnore
}
/**
* @param array<mixed, mixed> $rawData
*
* @return non-empty-array<non-empty-string, non-empty-string>|null
*/
private function getPrimaryKey(array $rawData, EntityDefinition $definition): ?array
{
$pk = [];
$pkFields = $definition->getPrimaryKeys();
foreach ($pkFields as $pkField) {
$propertyName = $pkField->getPropertyName();
if ($propertyName === '') {
return null; // @codeCoverageIgnore
}
$value = $rawData[$propertyName] ?? null;
if (!is_string($value) || $value === '') {
return null; // @codeCoverageIgnore
}
$pk[$propertyName] = $value;
}
if ($pk === []) {
return null; // @codeCoverageIgnore
}
return $pk;
}
/**
* @return array<non-empty-string, true>
*/
private function getPrimaryKeyFields(EntityDefinition $reference): array
{
$fields = [];
foreach ($reference->getPrimaryKeys() as $primaryKey) {
if (
$primaryKey instanceof VersionField
|| $primaryKey instanceof FkField && $primaryKey->getReferenceDefinition() instanceof VersionDefinition
) {
continue;
}
$propertyName = $primaryKey->getPropertyName();
if ($propertyName === '') {
throw new RuntimeException('Primary property name is empty!'); // @codeCoverageIgnore
}
$fields[$propertyName] = true;
}
return $fields;
}
/**
* @param array<mixed, mixed> $rawData
*
* @return array<mixed, mixed>
*/
private function getRelevantRawData(Field $field, array $rawData): array
{
if (!$field->is(Extension::class)) {
return $rawData;
}
$propertyName = $field->getPropertyName();
if (isset($rawData[$propertyName])) {
return $rawData;
}
if (
!isset($rawData['extensions'])
|| !is_array($rawData['extensions'])
|| !isset($rawData['extensions'][$propertyName])) {
return $rawData;
}
return $rawData['extensions'];
}
/**
* @param array<mixed, mixed> $rawData
*/
private function registerFieldForCleanup(
RelevantField $relevantField,
array $rawData,
): void {
$field = $relevantField->field;
$fieldData = $rawData[$field->getPropertyName()] ?? null;
if (!is_array($fieldData)) {
return;
}
$cleanupEnableField = $this->getCleanupEnableFieldName($field);
if (!array_key_exists($cleanupEnableField, $rawData)) {
return;
}
$cleanupEnabled = is_bool($rawData[$cleanupEnableField]) && $rawData[$cleanupEnableField];
unset($rawData[$cleanupEnableField]);
if (!$cleanupEnabled) {
return;
}
$this->registerRelationsForField($relevantField, $fieldData);
}
/**
* @param array<mixed, mixed> $rawData
*/
private function registerRelations(array $rawData, WriteParameterBag $parameters): void
{
$definition = $parameters->getDefinition();
$primaryKeys = $this->getPrimaryKey($rawData, $definition);
if ($primaryKeys === null) {
return; // @codeCoverageIgnore
}
// New entities do not need cleanup.
if (empty($parameters->getPrimaryKeyBag()->getExistenceState($parameters->getDefinition(), $primaryKeys))) {
return;
}
$primaryKeys = $this->filterVersionFields($primaryKeys, $definition);
foreach ($definition->getFields() as $field) {
$relevantField = RelevantField::create($field, $primaryKeys);
if ($relevantField === null) {
continue;
}
$rawData = $this->getRelevantRawData($field, $rawData);
$this->registerFieldForCleanup($relevantField, $rawData);
}
}
/**
* @param array<mixed, mixed> $fieldData
*/
private function registerRelationsForField(
RelevantField $relevantField,
array $fieldData,
): void {
$field = $relevantField->field;
$parentPrimaryKey = $relevantField->parentPrimaryKey;
$reference = $field->getReferenceDefinition();
$cleanupRelationData = match ($field instanceof OneToManyAssociationField) {
true => $this->buildCleanupDataForOneToManyAssociation($field, $parentPrimaryKey),
false => $this->buildCleanupDataForManyToManyAssociation($field, $parentPrimaryKey),
};
foreach ($fieldData as $referenceData) {
if (!is_array($referenceData)) {
continue; // @codeCoverageIgnore
}
$referencePrimaryKey = $this->getPrimaryKey($referenceData, $reference);
if ($referencePrimaryKey === null) {
return; // @codeCoverageIgnore
}
$referencePrimaryKey = $this->filterVersionFields($referencePrimaryKey, $reference);
$cleanupRelationData->addReferencedPrimaryKey($referencePrimaryKey);
}
$this->cleanupRelationsRegistry->registerRelationsForField($cleanupRelationData);
}
}