Passed
Pull Request — master (#195)
by
unknown
19:02
created

JsonToDocumentMapper::getMetadataFromJson()   F

Complexity

Conditions 17
Paths 492

Size

Total Lines 97
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 55
c 1
b 0
f 0
nc 492
nop 2
dl 0
loc 97
rs 1.7555

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace EWW\Dpf\Services\Api;
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\Document;
18
use EWW\Dpf\Services\ProcessNumber\ProcessNumberGenerator;
19
use JsonPath\JsonObject;
0 ignored issues
show
Bug introduced by
The type JsonPath\JsonObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
21
class JsonToDocumentMapper
22
{
23
    /**
24
     * objectManager
25
     *
26
     * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
27
     * @inject
28
     */
29
    protected $objectManager;
30
31
    /**
32
     * documentTypeRepository
33
     *
34
     * @var \EWW\Dpf\Domain\Repository\DocumentTypeRepository
35
     * @inject
36
     */
37
    protected $documentTypeRepository = null;
38
39
    /**
40
     * documentRepository
41
     *
42
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
43
     * @inject
44
     */
45
    protected $documentRepository = null;
46
47
    /**
48
     * Replaces the data from the document with the data from the json
49
     * @param Document $document
50
     * @param $jsonData
51
     * @return Document
52
     */
53
    public function editDocument(Document $document, $jsonData) {
54
55
        $metaData = $this->getMetadataFromJson($jsonData, $document->getDocumentType());
56
        $xmlData = $document->getXmlData();
57
58
        $domDocument = new \DOMDocument();
59
        $domDocument->loadXML($xmlData);
60
61
        $xpath = \EWW\Dpf\Helper\XPath::create($domDocument);
62
63
        foreach ($metaData as $groupKey => $group) {
64
            $groupMapping = $group['mapping'];
65
            if ($group['values']) {
66
                foreach ($group['values'] as $fieldKey => $field) {
67
                    $nodes = $xpath->query($groupMapping .'/'. $field['mapping']);
68
                    $nodes->item(0)->nodeValue = $field['value'];
69
                }
70
            }
71
        }
72
73
        $xmlData = $domDocument->saveXML();
74
        $document->setXmlData($xmlData);
75
76
        return $document;
77
    }
78
79
    /**
80
     * Creates a document from the given json data
81
     *
82
     * @param string $jsonData
83
     * @return Document $document
84
     */
85
    public function getDocument($jsonData)
86
    {
87
        $jsonObject = new JsonObject($jsonData);
88
        $publicationType = $jsonObject->get('$.publicationType');
89
90
        if ($publicationType && is_array($publicationType)) {
91
            $publicationType = $publicationType[0];
92
        }
93
94
        $documentType = $this->documentTypeRepository->findOneByName($publicationType);
0 ignored issues
show
Bug introduced by
The method findOneByName() does not exist on EWW\Dpf\Domain\Repository\DocumentTypeRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

94
        /** @scrutinizer ignore-call */ 
95
        $documentType = $this->documentTypeRepository->findOneByName($publicationType);
Loading history...
95
        if (!$documentType) {
96
            return null;
97
        }
98
99
        /** @var Document $document */
100
        $document = $this->objectManager->get(Document::class);
101
102
        $document->setDocumentType($documentType);
103
104
        $processNumberGenerator = $this->objectManager->get(ProcessNumberGenerator::class);
105
        $processNumber = $processNumberGenerator->getProcessNumber();
106
        $document->setProcessNumber($processNumber);
107
108
        $metaData = $this->getMetadataFromJson($jsonData);
109
110
        $exporter = new \EWW\Dpf\Services\ParserGenerator();
111
112
        $documentData['documentUid'] = 0;
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...
113
        $documentData['metadata']    = $metaData;
114
        $documentData['files']       = array();
115
116
        $exporter->buildXmlFromForm($documentData);
117
118
        $internalXml = $exporter->getXMLData();
119
        $document->setXmlData($internalXml);
120
121
        $internalFormat = new \EWW\Dpf\Helper\InternalFormat($internalXml);
122
123
        $document->setTitle($internalFormat->getTitle());
124
        $document->setAuthors($internalFormat->getAuthors());
125
        $document->setDateIssued($internalFormat->getDateIssued());
126
        //$document->setEmbargoDate($formMetaData['embargo']);
127
128
        $internalFormat->setDocumentType($documentType->getName());
0 ignored issues
show
Bug introduced by
The method getName() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

128
        $internalFormat->setDocumentType($documentType->/** @scrutinizer ignore-call */ getName());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
129
        $internalFormat->setProcessNumber($document->getProcessNumber());
130
131
        $document->setXmlData($internalFormat->getXml());
132
133
        $document->setState(\EWW\Dpf\Domain\Workflow\DocumentWorkflow::STATE_REGISTERED_NONE);
134
135
        return $document;
136
    }
137
138
139
    public function getMetadataFromJson($jsonData, $documentType = null)
140
    {
141
        $jsonObject = new JsonObject($jsonData);
142
143
        if ($documentType) {
144
            $publicationType = $documentType;
0 ignored issues
show
Unused Code introduced by
The assignment to $publicationType is dead and can be removed.
Loading history...
145
        } else {
146
            $publicationType = $jsonObject->get('$.publicationType');
147
            if ($publicationType && is_array($publicationType)) {
148
                $publicationType = $publicationType[0];
149
            }
150
151
            /** @var \EWW\Dpf\Domain\Model\DocumentType $documentType */
152
            $documentType = $this->documentTypeRepository->findOneByName($publicationType);
153
        }
154
155
        $resultData = [];
156
157
        if (empty($documentType)) {
158
            // default type
159
            $documentType = $this->documentTypeRepository->findOneByName('article');
160
        }
161
162
        foreach ($documentType->getMetadataPage() as $metadataPage) {
163
164
            foreach ($metadataPage->getMetadataGroup() as $metadataGroup) {
165
166
                // Group mapping
167
                $jsonDataObject = new JsonObject($jsonData);
168
                $jsonGroupMapping = $metadataGroup->getJsonMapping();
169
                $groupItems = [];
170
                if ($jsonGroupMapping) {
171
                    $groupItems = $jsonDataObject->get($jsonGroupMapping);
172
                }
173
174
                foreach ($groupItems as $groupItem) {
175
176
                    $resultGroup = [
177
                        'attributes' => [],
178
                        'values' => []
179
                    ];
180
                    $resultGroup['mapping'] = $metadataGroup->getRelativeMapping();
181
                    $resultGroup['modsExtensionMapping'] = $metadataGroup->getRelativeModsExtensionMapping();
182
                    $resultGroup['modsExtensionReference'] = trim($metadataGroup->getModsExtensionReference(), " /");
183
                    $resultGroup['groupUid'] = $metadataGroup->getUid();
184
185
                    foreach ($metadataGroup->getMetadataObject() as $metadataObject) {
186
187
                        $json = json_encode($groupItem);
188
189
                        $jsonObject = new JsonObject($json);
190
                        $fieldItems = [];
191
                        $jsonFieldMapping = $metadataObject->getJsonMapping();
192
193
                        if ($jsonFieldMapping) {
194
                            $fieldItems = $jsonObject->get($jsonFieldMapping);
195
                        }
196
197
                        foreach ($fieldItems as $fieldItem) {
198
                            $resultField = [];
199
200
                            if (!is_array($fieldItem)) {
201
                                $value = $fieldItem;
202
                            } else {
203
                                $value = implode("; ", $fieldItem);
204
                            }
205
206
                            if ($metadataObject->getDataType() == \EWW\Dpf\Domain\Model\MetadataObject::INPUT_DATA_TYPE_DATE) {
207
                                $date = date_create_from_format('d.m.Y', trim($value));
208
                                if ($date) {
209
                                    $value = date_format($date, 'Y-m-d');
210
                                }
211
                            }
212
213
                            if ($value) {
214
                                $value = str_replace('"', "'", $value);
215
                                $fieldMapping = $metadataObject->getRelativeMapping();
216
                                $resultField['modsExtension'] = $metadataObject->getModsExtension();
217
                                $resultField['mapping'] = $fieldMapping;
218
                                $resultField['value']   = $value;
219
220
                                if (strpos($fieldMapping, "@") === 0) {
221
                                    $resultGroup['attributes'][] = $resultField;
222
                                } else {
223
                                    $resultGroup['values'][] = $resultField;
224
                                }
225
                            }
226
                        }
227
                    }
228
229
                    $resultData[] = $resultGroup;;
230
                }
231
232
            }
233
        }
234
235
        return $resultData;
236
    }
237
238
}
239