Passed
Pull Request — master (#209)
by
unknown
33:50 queued 24:56
created

DocumentMapper::isCustomClientPid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
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
                            $objectMapping = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $objectMapping is dead and can be removed.
Loading history...
248
249
                            preg_match_all('/([A-Za-z0-9]+:[A-Za-z0-9]+(\[.*\])*|[A-Za-z0-9:@\.]+)/', $metadataObject->getRelativeMapping(), $objectMappingPath);
250
                            $objectMappingPath = $objectMappingPath[0];
251
252
                            foreach ($objectMappingPath as $key => $value) {
0 ignored issues
show
Comprehensibility Bug introduced by
$key is overwriting a variable from outer foreach loop.
Loading history...
253
254
                                // ensure that e.g. <mods:detail> and <mods:detail type="volume">
255
                                // are not recognized as the same node
256
                                if ((strpos($value, "@") === false) && ($value != '.')) {
257
                                    $objectMappingPath[$key] .= "[not(@*)]";
258
                                }
259
                            }
260
261
                            $objectMapping = implode("/", $objectMappingPath);
262
263
                            if ($objectMapping == '[not(@*)]' || empty($objectMappingPath)) {
264
                                $objectMapping = '.';
265
                            }
266
267
                            if ($metadataObject->isModsExtension()) {
268
269
                                $referenceAttribute        = $metadataGroup->getModsExtensionReference();
270
                                $modsExtensionGroupMapping = $metadataGroup->getAbsoluteModsExtensionMapping();
271
272
                                $refID      = $data->getAttribute("ID");
273
                                // filter hashes from referenceAttribute value for backwards compatibility reasons
274
                                $objectData = $xpath->query($modsExtensionGroupMapping . "[translate(@" . $referenceAttribute . ",'#','')=" . '"' . $refID . '"]/' . $objectMapping);
275
                            } else {
276
                                $objectData = $xpath->query($objectMapping, $data);
277
                            }
278
279
                            $documentFormField->setValue("", $metadataObject->getDefaultValue());
280
281
                            if ($objectData->length > 0) {
282
283
                                foreach ($objectData as $key => $value) {
284
285
                                    $documentFormFieldItem = clone ($documentFormField);
286
287
                                    $objectValue = $value->nodeValue;
288
289
                                    if ($metadataObject->getDataType() == \EWW\Dpf\Domain\Model\MetadataObject::INPUT_DATA_TYPE_DATE) {
290
                                        $dateStr = explode('T', $objectValue);
291
                                        $date    = date_create_from_format('Y-m-d', trim($dateStr[0]));
292
                                        if ($date) {
293
                                            $objectValue = date_format($date, 'd.m.Y');
294
                                        }
295
                                    }
296
297
                                    $objectValue = str_replace('"', "'", $objectValue);
298
299
                                    $documentFormFieldItem->setValue($objectValue, $metadataObject->getDefaultValue());
300
301
                                    $documentFormGroupItem->addItem($documentFormFieldItem);
302
                                }
303
                            } else {
304
                                $documentFormGroupItem->addItem($documentFormField);
305
                            }
306
307
                        }
308
309
                        $documentFormPage->addItem($documentFormGroupItem);
310
                    }
311
                } else {
312
313
                    $documentFormGroup->setEmptyGroup(true);
314
315
                    foreach ($metadataGroup->getMetadataObject() as $metadataObject) {
316
                        $documentFormField = new \EWW\Dpf\Domain\Model\DocumentFormField();
317
                        $documentFormField->setUid($metadataObject->getUid());
318
                        $documentFormField->setDisplayName($metadataObject->getDisplayName());
319
                        $documentFormField->setName($metadataObject->getName());
320
                        $documentFormField->setMandatory($metadataObject->getMandatory());
321
322
                        $documentFormField->setAccessRestrictionRoles($metadataObject->getAccessRestrictionRoles());
323
324
                        $documentFormField->setConsent($metadataObject->getConsent());
325
                        $documentFormField->setValidation($metadataObject->getValidation());
326
                        $documentFormField->setDataType($metadataObject->getDataType());
327
                        $documentFormField->setMaxIteration($metadataObject->getMaxIteration());
328
                        $documentFormField->setInputField($metadataObject->getInputField());
329
                        $documentFormField->setInputOptions($metadataObject->getInputOptionList());
330
                        $documentFormField->setFillOutService($metadataObject->getFillOutService());
331
                        $documentFormField->setGndFieldUid($metadataObject->getGndFieldUid());
332
                        $documentFormField->setMaxInputLength($metadataObject->getMaxInputLength());
333
                        $documentFormField->setValue("", $metadataObject->getDefaultValue());
334
                        $documentFormField->setObjectType($metadataObject->getObjectType());
335
336
                        $depositLicense = $this->depositLicenseRepository->findByUid($metadataObject->getDepositLicense());
337
                        $documentFormField->setDepositLicense($depositLicense);
338
339
                        $documentFormGroup->addItem($documentFormField);
340
                    }
341
342
                    $documentFormPage->addItem($documentFormGroup);
343
                }
344
            }
345
346
            $documentForm->addItem($documentFormPage);
347
        }
348
349
        // Files
350
        $primaryFile = $this->fileRepository->getPrimaryFileByDocument($document);
351
        $documentForm->setPrimaryFile($primaryFile);
352
353
        $secondaryFiles = $this->fileRepository->getSecondaryFilesByDocument($document)->toArray();
354
        $documentForm->setSecondaryFiles($secondaryFiles);
355
356
        return $documentForm;
357
    }
358
359
    public function getDocument($documentForm)
360
    {
361
        /** @var Document $document */
362
363
        if ($documentForm->getDocumentUid()) {
364
            if ($this->isCustomClientPid()) {
365
                $this->documentRepository->crossClient(true);
366
            }
367
            $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
368
            $tempInternalFormat = new \EWW\Dpf\Helper\InternalFormat($document->getXmlData(), $this->clientPid);
369
            $fobIdentifiers = $tempInternalFormat->getPersonFisIdentifiers();
370
        } else {
371
            $document = $this->objectManager->get(Document::class);
372
            $fobIdentifiers = [];
373
        }
374
375
        $processNumber = $document->getProcessNumber();
376
        if (empty($processNumber)) {
377
            $processNumberGenerator = $this->objectManager->get(ProcessNumberGenerator::class);
378
            $processNumber = $processNumberGenerator->getProcessNumber();
379
            $document->setProcessNumber($processNumber);
380
        }
381
382
        $documentType = $this->documentTypeRepository->findByUid($documentForm->getUid());
383
384
        $document->setDocumentType($documentType);
385
386
        $document->setReservedObjectIdentifier($documentForm->getFedoraPid());
387
388
        $document->setValid($documentForm->getValid());
389
390
        if ($documentForm->getComment()) {
391
            $document->setComment($documentForm->getComment());
392
        }
393
394
        $formMetaData = $this->getMetadata($documentForm);
395
396
        $exporter = new \EWW\Dpf\Services\ParserGenerator($this->clientPid);
397
398
        $exporter->setFileData($document->getFileData());
399
400
        $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...
401
        $documentData['metadata']    = $formMetaData['mods'];
402
        $documentData['files']       = array();
403
404
        $exporter->buildXmlFromForm($documentData);
405
406
        $internalXml = $exporter->getXmlData();
407
        $internalFormat = new \EWW\Dpf\Helper\InternalFormat($internalXml, $this->clientPid);
408
409
        // set static xml
410
        $internalFormat->setDocumentType($documentType->getName());
411
        $internalFormat->setProcessNumber($processNumber);
412
413
        $document->setXmlData($internalFormat->getXml());
414
415
        $document->setNewlyAssignedFobIdentifiers(array_diff($internalFormat->getPersonFisIdentifiers(), $fobIdentifiers));
416
417
        $document->setTitle($internalFormat->getTitle());
418
        $document->setEmbargoDate($formMetaData['embargo']);
419
        $document->setAuthors($internalFormat->getAuthors());
420
        $document->setDateIssued($internalFormat->getDateIssued());
421
422
        return $document;
423
    }
424
425
    public function getMetadata($documentForm)
426
    {
427
428
        foreach ($documentForm->getItems() as $page) {
429
430
            foreach ($page[0]->getItems() as $group) {
431
432
                foreach ($group as $groupItem) {
433
434
                    $item = array();
435
436
                    $uid           = $groupItem->getUid();
437
                    $metadataGroup = $this->metadataGroupRepository->findByUid($uid);
438
439
                    $item['mapping'] = $metadataGroup->getRelativeMapping();
440
441
                    $item['modsExtensionMapping'] = $metadataGroup->getRelativeModsExtensionMapping();
442
443
                    $item['modsExtensionReference'] = trim($metadataGroup->getModsExtensionReference(), " /");
444
445
                    $item['groupUid'] = $uid;
446
447
                    $fieldValueCount   = 0;
448
                    $defaultValueCount = 0;
449
                    $fieldCount        = 0;
450
                    foreach ($groupItem->getItems() as $field) {
451
                        foreach ($field as $fieldItem) {
452
                            $fieldUid       = $fieldItem->getUid();
453
                            $metadataObject = $this->metadataObjectRepository->findByUid($fieldUid);
454
455
                            $fieldMapping = $metadataObject->getRelativeMapping();
456
457
                            $formField = array();
458
459
                            $value = $fieldItem->getValue();
460
461
                            if ($metadataObject->getDataType() == \EWW\Dpf\Domain\Model\MetadataObject::INPUT_DATA_TYPE_DATE) {
462
                                $date = date_create_from_format('d.m.Y', trim($value));
463
                                if ($date) {
464
                                    $value = date_format($date, 'Y-m-d');
465
                                }
466
                            }
467
468
                            if ($metadataObject->getEmbargo()) {
469
                                $form['embargo'] = new \DateTime($value);
470
                            }
471
472
                            $fieldCount++;
473
                            if (!empty($value)) {
474
                                $fieldValueCount++;
475
                                $defaultValue = $fieldItem->getHasDefaultValue();
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultValue is dead and can be removed.
Loading history...
476
                                if ($fieldItem->getHasDefaultValue()) {
477
                                    $defaultValueCount++;
478
                                }
479
                            }
480
481
                            $value = str_replace('"', "'", $value);
482
                            if ($value) {
483
                                $formField['modsExtension'] = $metadataObject->getModsExtension();
484
485
                                $formField['mapping'] = $fieldMapping;
486
                                $formField['value']   = $value;
487
488
                                if (strpos($fieldMapping, "@") === 0) {
489
                                    $item['attributes'][] = $formField;
490
                                } else {
491
                                    $item['values'][] = $formField;
492
                                }
493
                            }
494
                        }
495
                    }
496
497
                    if (!key_exists('attributes', $item)) {
498
                        $item['attributes'] = array();
499
                    }
500
501
                    if (!key_exists('values', $item)) {
502
                        $item['values'] = array();
503
                    }
504
505
                    if ($groupItem->getMandatory() || $defaultValueCount < $fieldValueCount || $defaultValueCount == $fieldCount) {
506
                        $form['mods'][] = $item;
507
                    }
508
509
                }
510
511
            }
512
        }
513
514
        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...
515
516
    }
517
518
    /**
519
     * @return int
520
     */
521
    public function getClientPid(): int
522
    {
523
        return $this->clientPid;
524
    }
525
526
    /**
527
     * @param int $clientPid
528
     */
529
    public function setClientPid(int $clientPid): void
530
    {
531
        $this->customClientPid = true;
532
        $this->clientPid = $clientPid;
533
    }
534
535
    /**
536
     * @return bool
537
     */
538
    public function isCustomClientPid(): bool
539
    {
540
        return $this->customClientPid;
541
    }
542
543
}
544