Passed
Pull Request — master (#207)
by
unknown
12:49
created

DocumentMapper   F

Complexity

Total Complexity 67

Size/Duplication

Total Lines 594
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 67
eloc 274
c 1
b 0
f 0
dl 0
loc 594
rs 3.04

8 Methods

Rating   Name   Duplication   Size   Complexity  
A isCustomClientPid() 0 3 1
F getMetadata() 0 100 20
A setClientPid() 0 4 1
A getSettings() 0 6 1
A getClientPid() 0 3 1
A getDocument() 0 62 5
F getDocumentForm() 0 251 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
     * clientPid
93
     *
94
     * @var int
95
     */
96
    protected $clientPid = 0;
97
98
    /**
99
     * @var bool
100
     */
101
    protected $customClientPid = false;
102
103
    /**
104
     * clientConfigurationManager
105
     *
106
     * @var \EWW\Dpf\Configuration\ClientConfigurationManager
107
     * @TYPO3\CMS\Extbase\Annotation\Inject
108
     */
109
    protected $clientConfigurationManager;
110
111
    /**
112
     * Get typoscript settings
113
     *
114
     * @return mixed
115
     */
116
    public function getSettings()
117
    {
118
        $frameworkConfiguration = $this->configurationManager->getConfiguration(
119
            \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
120
        );
121
        return $frameworkConfiguration['settings'];
122
    }
123
124
    /**
125
     * Gets the document form representation of the document data
126
     *
127
     * @param \EWW\Dpf\Domain\Model\Document $document
128
     * @param bool $generateEmptyFields
129
     * @return \EWW\Dpf\Domain\Model\DocumentForm
130
     */
131
    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

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