Passed
Pull Request — master (#207)
by
unknown
16:03 queued 05:02
created

DocumentMapper   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 550
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 63
eloc 264
dl 0
loc 550
rs 3.36
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
F getMetadata() 0 100 20
A getSettings() 0 6 1
A getDocument() 0 59 4
F getDocumentForm() 0 247 32
A updateFiles() 0 29 6

How to fix   Complexity   

Complex Class

Complex classes like DocumentMapper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DocumentMapper, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace EWW\Dpf\Helper;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use EWW\Dpf\Domain\Model\MetadataGroup;
18
use EWW\Dpf\Domain\Model\DocumentForm;
19
use EWW\Dpf\Domain\Model\File;
20
use EWW\Dpf\Services\Identifier\Urn;
21
use EWW\Dpf\Domain\Model\Document;
22
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
23
use EWW\Dpf\Services\ProcessNumber\ProcessNumberGenerator;
24
25
class DocumentMapper
26
{
27
28
    /**
29
     * objectManager
30
     *
31
     * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
32
     * @TYPO3\CMS\Extbase\Annotation\Inject
33
     */
34
    protected $objectManager;
35
36
    /**
37
     *
38
     * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
39
     * @TYPO3\CMS\Extbase\Annotation\Inject
40
     */
41
    protected $configurationManager;
42
43
    /**
44
     * metadataGroupRepository
45
     *
46
     * @var \EWW\Dpf\Domain\Repository\MetadataGroupRepository
47
     * @TYPO3\CMS\Extbase\Annotation\Inject
48
     */
49
    protected $metadataGroupRepository = null;
50
51
    /**
52
     * metadataObjectRepository
53
     *
54
     * @var \EWW\Dpf\Domain\Repository\MetadataObjectRepository
55
     * @TYPO3\CMS\Extbase\Annotation\Inject
56
     */
57
    protected $metadataObjectRepository = null;
58
59
    /**
60
     * documentTypeRepository
61
     *
62
     * @var \EWW\Dpf\Domain\Repository\DocumentTypeRepository
63
     * @TYPO3\CMS\Extbase\Annotation\Inject
64
     */
65
    protected $documentTypeRepository = null;
66
67
    /**
68
     * documentRepository
69
     *
70
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
71
     * @TYPO3\CMS\Extbase\Annotation\Inject
72
     */
73
    protected $documentRepository = null;
74
75
    /**
76
     * fileRepository
77
     *
78
     * @var \EWW\Dpf\Domain\Repository\FileRepository
79
     * @TYPO3\CMS\Extbase\Annotation\Inject
80
     */
81
    protected $fileRepository = null;
82
83
    /**
84
     * depositLicenseRepository
85
     *
86
     * @var \EWW\Dpf\Domain\Repository\DepositLicenseRepository
87
     * @TYPO3\CMS\Extbase\Annotation\Inject
88
     */
89
    protected $depositLicenseRepository = null;
90
91
    /**
92
     * clientConfigurationManager
93
     *
94
     * @var \EWW\Dpf\Configuration\ClientConfigurationManager
95
     * @TYPO3\CMS\Extbase\Annotation\Inject
96
     */
97
    protected $clientConfigurationManager;
98
99
    /**
100
     * Get typoscript settings
101
     *
102
     * @return mixed
103
     */
104
    public function getSettings()
105
    {
106
        $frameworkConfiguration = $this->configurationManager->getConfiguration(
107
            \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
108
        );
109
        return $frameworkConfiguration['settings'];
110
    }
111
112
    /**
113
     * Gets the document form representation of the document data
114
     *
115
     * @param \EWW\Dpf\Domain\Model\Document $document
116
     * @param bool $generateEmptyFields
117
     * @return \EWW\Dpf\Domain\Model\DocumentForm
118
     */
119
    public function getDocumentForm(Document $document, $generateEmptyFields = true)
0 ignored issues
show
Unused Code introduced by
The parameter $generateEmptyFields is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

119
    public function getDocumentForm(Document $document, /** @scrutinizer ignore-unused */ $generateEmptyFields = true)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
120
    {
121
        $documentForm = new \EWW\Dpf\Domain\Model\DocumentForm();
122
        $documentForm->generateCsrfToken();
123
        $documentForm->setUid($document->getDocumentType()->getUid());
124
        $documentForm->setDisplayName($document->getDocumentType()->getDisplayName());
125
        $documentForm->setName($document->getDocumentType()->getName());
126
        $documentForm->setDocumentUid($document->getUid());
127
128
        $documentForm->setPrimaryFileMandatory(
129
            (
130
                (
131
                    $this->getSettings()['deactivatePrimaryFileMandatoryCheck'] ||
132
                    $document->getDocumentType()->getVirtualType()
133
                )? false : true
134
            )
135
        );
136
137
        $documentForm->setProcessNumber($document->getProcessNumber());
138
        $documentForm->setTemporary($document->isTemporary());
139
140
        $fedoraPid = $document->getObjectIdentifier();
141
142
        if (empty($fedoraPid)) {
143
            $fedoraPid = $document->getReservedObjectIdentifier();
144
        }
145
146
        $documentForm->setFedoraPid($fedoraPid);
147
148
        $internalFormat = new \EWW\Dpf\Helper\InternalFormat($document->getXmlData());
149
150
        $excludeGroupAttributes = array();
151
152
        foreach ($document->getDocumentType()->getMetadataPage() as $metadataPage) {
153
            $documentFormPage = new \EWW\Dpf\Domain\Model\DocumentFormPage();
154
            $documentFormPage->setUid($metadataPage->getUid());
155
            $documentFormPage->setDisplayName($metadataPage->getDisplayName());
156
            $documentFormPage->setName($metadataPage->getName());
157
158
            $documentFormPage->setAccessRestrictionRoles($metadataPage->getAccessRestrictionRoles());
159
160
            foreach ($metadataPage->getMetadataGroup() as $metadataGroup) {
161
                /** @var MetadataGroup $metadataGroup */
162
163
                $documentFormGroup = new \EWW\Dpf\Domain\Model\DocumentFormGroup();
164
                $documentFormGroup->setUid($metadataGroup->getUid());
165
                $documentFormGroup->setDisplayName($metadataGroup->getDisplayName());
166
                $documentFormGroup->setName($metadataGroup->getName());
167
                $documentFormGroup->setMandatory($metadataGroup->getMandatory());
168
169
                $documentFormGroup->setAccessRestrictionRoles($metadataGroup->getAccessRestrictionRoles());
170
171
                $documentFormGroup->setInfoText($metadataGroup->getInfoText());
172
                $documentFormGroup->setGroupType($metadataGroup->getGroupType());
173
                $documentFormGroup->setMaxIteration($metadataGroup->getMaxIteration());
174
175
                $documentFormGroup->setOptionalGroups($metadataGroup->getOptionalGroups());
176
                $documentFormGroup->setRequiredGroups($metadataGroup->getRequiredGroups());
177
178
                $xpath = $internalFormat->getXpath();
179
180
                // get fixed attributes from xpath configuration
181
                $fixedGroupAttributes = array();
182
183
                preg_match_all('/[A-Za-z0-9:@\.]+(\[@.*?\])*/', $metadataGroup->getAbsoluteMapping(), $groupMappingPathParts);
184
                $groupMappingPathParts = $groupMappingPathParts[0];
185
186
                $groupMappingPath = end($groupMappingPathParts);
187
                $groupMappingName = preg_replace('/\[@.+?\]/', '', $groupMappingPath);
188
189
                if (preg_match_all('/\[@.+?\]/', $groupMappingPath, $matches)) {
190
                    $fixedGroupAttributes = $matches[0];
191
                }
192
193
                // build mapping path, previous fixed attributes which are differ from
194
                // the own fixed attributes are excluded
195
                $queryGroupMapping = $metadataGroup->getAbsoluteMapping();
196
                if (strpos($queryGroupMapping, "@displayLabel") === false && is_array($excludeGroupAttributes[$groupMappingName])) {
197
                    foreach ($excludeGroupAttributes[$groupMappingName] as $excludeAttr => $excludeAttrValue) {
198
                        if (!in_array($excludeAttr, $fixedGroupAttributes)) {
199
                            $queryGroupMapping .= $excludeAttrValue;
200
                        }
201
                    }
202
                }
203
204
                // Read the group data.
205
                if ($metadataGroup->hasMappingForReading()) {
206
                    $groupData = $xpath->query($metadataGroup->getAbsoluteMappingForReading());
207
                } else {
208
                    $groupData = $xpath->query($queryGroupMapping);
209
                }
210
211
                // Fixed attributes from groups must be excluded in following xpath queries
212
                foreach ($fixedGroupAttributes as $excludeGroupAttribute) {
213
                    $excludeGroupAttributes[$groupMappingName][$excludeGroupAttribute] = "[not(" . trim($excludeGroupAttribute, "[] ") . ")]";
214
                }
215
216
                if ($groupData->length > 0) {
217
                    foreach ($groupData as $key => $data) {
218
219
                        $documentFormGroupItem = clone ($documentFormGroup);
220
221
                        foreach ($metadataGroup->getMetadataObject() as $metadataObject) {
222
223
                            $documentFormField = new \EWW\Dpf\Domain\Model\DocumentFormField();
224
                            $documentFormField->setUid($metadataObject->getUid());
225
                            $documentFormField->setDisplayName($metadataObject->getDisplayName());
226
                            $documentFormField->setName($metadataObject->getName());
227
                            $documentFormField->setMandatory($metadataObject->getMandatory());
228
229
                            $documentFormField->setAccessRestrictionRoles($metadataObject->getAccessRestrictionRoles());
230
231
                            $documentFormField->setConsent($metadataObject->getConsent());
232
                            $documentFormField->setValidation($metadataObject->getValidation());
233
                            $documentFormField->setDataType($metadataObject->getDataType());
234
                            $documentFormField->setMaxIteration($metadataObject->getMaxIteration());
235
                            $documentFormField->setInputField($metadataObject->getInputField());
236
                            $documentFormField->setInputOptions($metadataObject->getInputOptionList());
237
                            $documentFormField->setFillOutService($metadataObject->getFillOutService());
238
                            $documentFormField->setGndFieldUid($metadataObject->getGndFieldUid());
239
                            $documentFormField->setMaxInputLength($metadataObject->getMaxInputLength());
240
                            $documentFormField->setObjectType($metadataObject->getObjectType());
241
242
                            $depositLicense = $this->depositLicenseRepository->findByUid($metadataObject->getDepositLicense());
243
                            $documentFormField->setDepositLicense($depositLicense);
244
245
                            $objectMapping = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $objectMapping is dead and can be removed.
Loading history...
246
247
                            preg_match_all('/([A-Za-z0-9]+:[A-Za-z0-9]+(\[.*\])*|[A-Za-z0-9:@\.]+)/', $metadataObject->getRelativeMapping(), $objectMappingPath);
248
                            $objectMappingPath = $objectMappingPath[0];
249
250
                            foreach ($objectMappingPath as $key => $value) {
0 ignored issues
show
Comprehensibility Bug introduced by
$key is overwriting a variable from outer foreach loop.
Loading history...
251
252
                                // ensure that e.g. <mods:detail> and <mods:detail type="volume">
253
                                // are not recognized as the same node
254
                                if ((strpos($value, "@") === false) && ($value != '.')) {
255
                                    $objectMappingPath[$key] .= "[not(@*)]";
256
                                }
257
                            }
258
259
                            $objectMapping = implode("/", $objectMappingPath);
260
261
                            if ($objectMapping == '[not(@*)]' || empty($objectMappingPath)) {
262
                                $objectMapping = '.';
263
                            }
264
265
                            if ($metadataObject->isModsExtension()) {
266
267
                                $referenceAttribute        = $metadataGroup->getModsExtensionReference();
268
                                $modsExtensionGroupMapping = $metadataGroup->getAbsoluteModsExtensionMapping();
269
270
                                $refID      = $data->getAttribute("ID");
271
                                // filter hashes from referenceAttribute value for backwards compatibility reasons
272
                                $objectData = $xpath->query($modsExtensionGroupMapping . "[translate(@" . $referenceAttribute . ",'#','')=" . '"' . $refID . '"]/' . $objectMapping);
273
                            } else {
274
                                $objectData = $xpath->query($objectMapping, $data);
275
                            }
276
277
                            $documentFormField->setValue("", $metadataObject->getDefaultValue());
278
279
                            if ($objectData->length > 0) {
280
281
                                foreach ($objectData as $key => $value) {
282
283
                                    $documentFormFieldItem = clone ($documentFormField);
284
285
                                    $objectValue = $value->nodeValue;
286
287
                                    if ($metadataObject->getDataType() == \EWW\Dpf\Domain\Model\MetadataObject::INPUT_DATA_TYPE_DATE) {
288
                                        $dateStr = explode('T', $objectValue);
289
                                        $date    = date_create_from_format('Y-m-d', trim($dateStr[0]));
290
                                        if ($date) {
291
                                            $objectValue = date_format($date, 'd.m.Y');
292
                                        }
293
                                    }
294
295
                                    $objectValue = str_replace('"', "'", $objectValue);
296
297
                                    $documentFormFieldItem->setValue($objectValue, $metadataObject->getDefaultValue());
298
299
                                    if ($metadataGroup->isFileGroup() && $metadataObject->isUploadField()) {
300
301
                                        $fileIdentifier = '';
302
                                        $fileIdXpath = $this->clientConfigurationManager->getFileIdXpath();
303
                                        $fileIdentifierNode = $xpath->query($fileIdXpath, $data);
304
                                        if ($fileIdentifierNode->length > 0) {
305
                                            $fileIdentifier = $fileIdentifierNode->item(0)->nodeValue;
306
                                        }
307
308
                                        if ($fileIdentifier) {
309
                                            $file = $document->getFileByFileIdentifier($fileIdentifier);
310
                                            if ($file) {
311
                                                $documentFormFieldItem->setFile($file);
312
                                                $documentForm->addFile($file);
313
                                            }
314
                                        }
315
                                    }
316
317
                                    $documentFormGroupItem->addItem($documentFormFieldItem);
318
                                }
319
                            } else {
320
                                $documentFormGroupItem->addItem($documentFormField);
321
                            }
322
323
                        }
324
325
                        $documentFormPage->addItem($documentFormGroupItem);
326
                    }
327
                } else {
328
329
                    $documentFormGroup->setEmptyGroup(true);
330
331
                    foreach ($metadataGroup->getMetadataObject() as $metadataObject) {
332
                        $documentFormField = new \EWW\Dpf\Domain\Model\DocumentFormField();
333
                        $documentFormField->setUid($metadataObject->getUid());
334
                        $documentFormField->setDisplayName($metadataObject->getDisplayName());
335
                        $documentFormField->setName($metadataObject->getName());
336
                        $documentFormField->setMandatory($metadataObject->getMandatory());
337
338
                        $documentFormField->setAccessRestrictionRoles($metadataObject->getAccessRestrictionRoles());
339
340
                        $documentFormField->setConsent($metadataObject->getConsent());
341
                        $documentFormField->setValidation($metadataObject->getValidation());
342
                        $documentFormField->setDataType($metadataObject->getDataType());
343
                        $documentFormField->setMaxIteration($metadataObject->getMaxIteration());
344
                        $documentFormField->setInputField($metadataObject->getInputField());
345
                        $documentFormField->setInputOptions($metadataObject->getInputOptionList());
346
                        $documentFormField->setFillOutService($metadataObject->getFillOutService());
347
                        $documentFormField->setGndFieldUid($metadataObject->getGndFieldUid());
348
                        $documentFormField->setMaxInputLength($metadataObject->getMaxInputLength());
349
                        $documentFormField->setValue("", $metadataObject->getDefaultValue());
350
                        $documentFormField->setObjectType($metadataObject->getObjectType());
351
352
                        $depositLicense = $this->depositLicenseRepository->findByUid($metadataObject->getDepositLicense());
353
                        $documentFormField->setDepositLicense($depositLicense);
354
355
                        $documentFormGroup->addItem($documentFormField);
356
                    }
357
358
                    $documentFormPage->addItem($documentFormGroup);
359
                }
360
            }
361
362
            $documentForm->addItem($documentFormPage);
363
        }
364
365
        return $documentForm;
366
    }
367
368
    public function getDocument($documentForm)
369
    {
370
        /** @var Document $document */
371
372
        if ($documentForm->getDocumentUid()) {
373
            $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
374
            $tempInternalFormat = new \EWW\Dpf\Helper\InternalFormat($document->getXmlData());
375
            $fobIdentifiers = $tempInternalFormat->getPersonFisIdentifiers();
376
        } else {
377
            $document = $this->objectManager->get(Document::class);
378
            $fobIdentifiers = [];
379
        }
380
381
        $processNumber = $document->getProcessNumber();
382
        if (empty($processNumber)) {
383
            $processNumberGenerator = $this->objectManager->get(ProcessNumberGenerator::class);
384
            $processNumber = $processNumberGenerator->getProcessNumber();
385
            $document->setProcessNumber($processNumber);
386
        }
387
388
        $documentType = $this->documentTypeRepository->findByUid($documentForm->getUid());
389
390
        $document->setDocumentType($documentType);
391
392
        $document->setReservedObjectIdentifier($documentForm->getFedoraPid());
393
394
        $document->setValid($documentForm->getValid());
395
396
        if ($documentForm->getComment()) {
397
            $document->setComment($documentForm->getComment());
398
        }
399
400
        $formMetaData = $this->getMetadata($documentForm);
401
402
        $exporter = new \EWW\Dpf\Services\ParserGenerator();
403
404
        $documentData['documentUid'] = $documentForm->getDocumentUid();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$documentData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $documentData = array(); before regardless.
Loading history...
405
        $documentData['metadata']    = $formMetaData['mods'];
406
407
        $exporter->buildXmlFromForm($documentData);
408
409
        $internalXml = $exporter->getXmlData();
410
        $internalFormat = new \EWW\Dpf\Helper\InternalFormat($internalXml);
411
412
        // set static xml
413
        $internalFormat->setDocumentType($documentType->getName());
414
        $internalFormat->setProcessNumber($processNumber);
415
416
        $document = $this->updateFiles($document, $documentForm->getFiles());
417
        $document->setXmlData($internalFormat->getXml());
418
419
        $document->setNewlyAssignedFobIdentifiers(array_diff($internalFormat->getPersonFisIdentifiers(), $fobIdentifiers));
420
421
        $document->setTitle($internalFormat->getTitle());
422
        $document->setEmbargoDate($formMetaData['embargo']);
423
        $document->setAuthors($internalFormat->getAuthors());
424
        $document->setDateIssued($internalFormat->getDateIssued());
425
426
        return $document;
427
    }
428
429
    /**
430
     * @param DocumentForm $documentForm
431
     * @return array
432
     * @throws \Exception
433
     */
434
    public function getMetadata(DocumentForm $documentForm)
435
    {
436
        foreach ($documentForm->getItems() as $page) {
437
438
            foreach ($page[0]->getItems() as $group) {
439
440
                foreach ($group as $groupItem) {
441
442
                    $item = array();
443
444
                    $uid           = $groupItem->getUid();
445
                    $metadataGroup = $this->metadataGroupRepository->findByUid($uid);
446
447
                    $item['mapping'] = $metadataGroup->getRelativeMapping();
448
449
                    $item['modsExtensionMapping'] = $metadataGroup->getRelativeModsExtensionMapping();
450
451
                    $item['modsExtensionReference'] = trim($metadataGroup->getModsExtensionReference(), " /");
452
453
                    $item['groupUid'] = $uid;
454
455
                    $item['groupType'] = $metadataGroup->getGroupType();
456
457
                    $fieldValueCount   = 0;
458
                    $defaultValueCount = 0;
459
                    $fieldCount        = 0;
460
                    foreach ($groupItem->getItems() as $field) {
461
                        foreach ($field as $fieldItem) {
462
                            $fieldUid       = $fieldItem->getUid();
463
                            $metadataObject = $this->metadataObjectRepository->findByUid($fieldUid);
464
465
                            $fieldMapping = $metadataObject->getRelativeMapping();
466
467
                            $formField = array();
468
469
                            $value = $fieldItem->getValue();
470
471
                            if ($metadataObject->getDataType() == \EWW\Dpf\Domain\Model\MetadataObject::INPUT_DATA_TYPE_DATE) {
472
                                $date = date_create_from_format('d.m.Y', trim($value));
473
                                if ($date) {
474
                                    $value = date_format($date, 'Y-m-d');
475
                                }
476
                            }
477
478
                            if ($metadataObject->getEmbargo()) {
479
                                $form['embargo'] = new \DateTime($value);
480
                            }
481
482
                            $fieldCount++;
483
                            if (!empty($value)) {
484
                                $fieldValueCount++;
485
                                $defaultValue = $fieldItem->getHasDefaultValue();
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultValue is dead and can be removed.
Loading history...
486
                                if ($fieldItem->getHasDefaultValue()) {
487
                                    $defaultValueCount++;
488
                                }
489
                            }
490
491
                            $file = $fieldItem->getFile();
492
                            $value = str_replace('"', "'", $value);
493
                            if ($value || $file) {
494
                                $formField['modsExtension'] = $metadataObject->getModsExtension();
495
496
                                $formField['mapping'] = $fieldMapping;
497
                                $formField['value']   = $value;
498
499
                                if (strpos($fieldMapping, "@") === 0) {
500
                                    $item['attributes'][] = $formField;
501
                                } else {
502
                                    $item['values'][] = $formField;
503
                                }
504
505
                                $fileIdXpath = $this->clientConfigurationManager->getFileIdXpath();
506
                                if ($file) {
507
                                    $item['values'][] = [
508
                                        'mapping' => $fileIdXpath,
509
                                        'value'   => $file->getFileIdentifier()
510
                                    ];
511
                                }
512
                            }
513
                        }
514
                    }
515
516
                    if (!key_exists('attributes', $item)) {
517
                        $item['attributes'] = array();
518
                    }
519
520
                    if (!key_exists('values', $item)) {
521
                        $item['values'] = array();
522
                    }
523
524
                    if ($groupItem->getMandatory() || $defaultValueCount < $fieldValueCount || $defaultValueCount == $fieldCount) {
525
                        $form['mods'][] = $item;
526
                    }
527
528
                }
529
530
            }
531
        }
532
533
        return $form;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $form does not seem to be defined for all execution paths leading up to this point.
Loading history...
534
535
    }
536
537
    /**
538
     * Adds and delete file model objects attached to the document.
539
     *
540
     * @param Document $document
541
     * @param array $files
542
     * @return Document
543
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
544
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException
545
     */
546
    protected function updateFiles(Document $document, $files)
547
    {
548
        $filesToBeDeleted = [];
549
        foreach ($document->getFile() as $docFile) {
550
            $filesToBeDeleted[$docFile->getFileIdentifier()] = $docFile;
551
        }
552
        // Add or update files
553
        /** @var File $file */
554
        foreach ($files as $file) {
555
            if ($file->getUid()) {
556
                $this->fileRepository->update($file);
557
            } else {
558
                $this->fileRepository->add($file);
559
                $document->addFile($file);
560
            }
561
562
            if (array_key_exists($file->getFileIdentifier(), $filesToBeDeleted)) {
563
                unset($filesToBeDeleted[$file->getFileIdentifier()]);
564
            }
565
        }
566
567
        // Delete files
568
        /** @var File $deleteFile */
569
        foreach ($filesToBeDeleted as $fileToBeDeleted) {
570
            $fileToBeDeleted->setStatus(File::STATUS_DELETED);
571
            $this->fileRepository->update($fileToBeDeleted);
572
        }
573
574
        return $document;
575
    }
576
577
578
}
579