Passed
Push — master ( 134b43...f02d33 )
by Ralf
09:50
created

DocumentMapper::setClientPid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 1
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\Services\Identifier\Urn;
19
use EWW\Dpf\Domain\Model\Document;
20
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
21
use EWW\Dpf\Services\ProcessNumber\ProcessNumberGenerator;
22
23
class DocumentMapper
24
{
25
26
    /**
27
     * objectManager
28
     *
29
     * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
30
     * @TYPO3\CMS\Extbase\Annotation\Inject
31
     */
32
    protected $objectManager;
33
34
    /**
35
     *
36
     * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
37
     * @TYPO3\CMS\Extbase\Annotation\Inject
38
     */
39
    protected $configurationManager;
40
41
    /**
42
     * metadataGroupRepository
43
     *
44
     * @var \EWW\Dpf\Domain\Repository\MetadataGroupRepository
45
     * @TYPO3\CMS\Extbase\Annotation\Inject
46
     */
47
    protected $metadataGroupRepository = null;
48
49
    /**
50
     * metadataObjectRepository
51
     *
52
     * @var \EWW\Dpf\Domain\Repository\MetadataObjectRepository
53
     * @TYPO3\CMS\Extbase\Annotation\Inject
54
     */
55
    protected $metadataObjectRepository = null;
56
57
    /**
58
     * documentTypeRepository
59
     *
60
     * @var \EWW\Dpf\Domain\Repository\DocumentTypeRepository
61
     * @TYPO3\CMS\Extbase\Annotation\Inject
62
     */
63
    protected $documentTypeRepository = null;
64
65
    /**
66
     * documentRepository
67
     *
68
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
69
     * @TYPO3\CMS\Extbase\Annotation\Inject
70
     */
71
    protected $documentRepository = null;
72
73
    /**
74
     * fileRepository
75
     *
76
     * @var \EWW\Dpf\Domain\Repository\FileRepository
77
     * @TYPO3\CMS\Extbase\Annotation\Inject
78
     */
79
    protected $fileRepository = null;
80
81
    /**
82
     * depositLicenseRepository
83
     *
84
     * @var \EWW\Dpf\Domain\Repository\DepositLicenseRepository
85
     * @TYPO3\CMS\Extbase\Annotation\Inject
86
     */
87
    protected $depositLicenseRepository = null;
88
89
    /**
90
     * clientPid
91
     *
92
     * @var int
93
     */
94
    protected $clientPid = 0;
95
96
    /**
97
     * @var bool
98
     */
99
    protected $customClientPid = false;
100
101
    /**
102
     * Get typoscript settings
103
     *
104
     * @return mixed
105
     */
106
    public function getSettings()
107
    {
108
        $frameworkConfiguration = $this->configurationManager->getConfiguration(
109
            \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
110
        );
111
        return $frameworkConfiguration['settings'];
112
    }
113
114
    /**
115
     * Gets the document form representation of the document data
116
     *
117
     * @param \EWW\Dpf\Domain\Model\Document $document
118
     * @param bool $generateEmptyFields
119
     * @return \EWW\Dpf\Domain\Model\DocumentForm
120
     */
121
    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

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