Passed
Pull Request — master (#195)
by
unknown
10:11 queued 02:49
created

BibTexFileImporter::getImporterName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace EWW\Dpf\Services\ImportExternalMetadata;
4
5
use Symfony\Component\Serializer\Encoder\XmlEncoder;
6
use EWW\Dpf\Domain\Model\BibTexMetadata;
7
use EWW\Dpf\Domain\Model\ExternalMetadata;
8
9
use RenanBr\BibTexParser\Listener;
10
use RenanBr\BibTexParser\Parser;
11
use RenanBr\BibTexParser\Processor;
12
13
class BibTexFileImporter extends AbstractImporter implements FileImporter
14
{
15
16
    /**
17
     * @var array
18
     */
19
    protected $mandatoryErrors = [];
20
21
    /**
22
     * Returns the list of all publication types
23
     *
24
     * @return array
25
     */
26
    public static function types()
27
    {
28
        return [
29
            'article',
30
            'book',
31
            'booklet',
32
            'inbook',
33
            'incollection',
34
            'inproceedings',
35
            'manual',
36
            'mastersthesis',
37
            'misc',
38
            'phdthesis',
39
            'proceedings',
40
            'techreport',
41
            'unpublished'
42
        ];
43
    }
44
45
    /**
46
     * @param string $file Can be a path to a file or a string with the file content
47
     * @param bool $contentOnly Determines if $file is a path or content as a string
48
     * @return array
49
     * @throws \ErrorException
50
     * @throws \RenanBr\BibTexParser\Exception\ParserException
51
     */
52
    protected function parseFile($file, $contentOnly = false)
53
    {
54
        //$data = json_decode($response->__toString(),true);
55
        //$encoder = new XmlEncoder();
56
        $listener = new Listener();
57
        $listener->addProcessor(new Processor\TagNameCaseProcessor(CASE_LOWER));
58
        $parser = new Parser();
59
        $parser->addListener($listener);
60
61
        if ($contentOnly) {
62
            $parser->parseString($file);
63
        } else {
64
            $parser->parseFile($file);
65
        }
66
67
        $entries = $listener->export();
68
69
        foreach ($entries as $index => $fields) {
70
            foreach ($fields as $key => $field) {
71
                $field = str_replace("{\\\"o}", "ö", $field);
72
                $field = str_replace("{\\\"O}", "Ö", $field);
73
                $field = str_replace("{\\\"a}", "ä", $field);
74
                $field = str_replace("{\\\"A}", "Ä", $field);
75
                $field = str_replace("{\\\"u}", "ü", $field);
76
                $field = str_replace("{\\\"U}", "Ü", $field);
77
                $field = str_replace("\\textendash", "-", $field);
78
                $field = str_replace("\\textemdash", "—", $field);
79
                $field = str_replace("\\textquoteright", "'", $field);
80
                $field = str_replace("\\textquoteleft", "'", $field);
81
                $field = str_replace("{\\ss}", "ß", $field);
82
                $field = preg_replace("/{\s*[\\\]textunderscore\s*}/", '_', $field);
83
                $field = preg_replace("/{\s*[\\\]textquotedbl\s*}/", '"', $field);
84
                $entries[$index][$key] = preg_replace("/{\s*[\\\]&\s*}/", '&', $field);
85
            }
86
        }
87
88
        return $entries;
89
    }
90
91
    /**
92
     * @param string $filePath
93
     * @param string $mandatoryFieldSettings
94
     * @param bool $contentOnly Determines if $file is a path or content as a string
95
     * @return array
96
     */
97
    public function loadFile($filePath, $mandatoryFieldSettings, $contentOnly = false)
98
    {
99
        $results = [];
100
        $mandatoryErrors = [];
101
        $mandatoryFieldErrors = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $mandatoryFieldErrors is dead and can be removed.
Loading history...
102
103
        $mandatoryFields = array_map(
104
            'trim',
105
            explode(',', $mandatoryFieldSettings)
106
        );
107
108
        foreach ($mandatoryFields as $key => $value) {
109
            $orFields = array_map(
110
                'trim',
111
                explode('|', $value)
112
            );
113
            $mandatoryFields[$key] = $orFields;
114
        }
115
116
        if ($contentOnly) {
117
            $bibTexEntries = $this->parseFile($filePath, $contentOnly);
118
        } else {
119
            $bibTexEntries = $this->parseFile($filePath);
120
        }
121
122
        $encoder = new XmlEncoder();
123
124
        foreach ($bibTexEntries as $index => $bibTexItem) {
125
126
            $mandatoryFieldErrors = [];
127
            foreach ($mandatoryFields as $combinedMandatoryField) {
128
129
                $mandatoryOk = false;
130
                foreach ($combinedMandatoryField as $key => $value) {
131
                    $mandatoryOk = $mandatoryOk || (
132
                            array_key_exists($value, $bibTexItem)
133
                            && $bibTexItem[$value]
134
                        );
135
                }
136
137
                if (!$mandatoryOk) {
138
                    $mandatoryFieldErrors[implode('|', $combinedMandatoryField)] = implode(
139
                        '|',
140
                        $combinedMandatoryField
141
                    );
142
                    $mandatoryErrors[$index] = [
143
                        'index' => $index + 1,
144
                        'title' => $bibTexItem['title'],
145
                        'fields' => $mandatoryFieldErrors
146
                    ];
147
                }
148
            }
149
150
            if (!$mandatoryErrors[$index]) {
151
152
                $bibTexData = $bibTexItem;
153
154
                if (array_key_exists('author', $bibTexItem)) {
155
                    $bibTexData['author'] = $this->splitPersons($bibTexItem['author']);
156
                }
157
158
                if (array_key_exists('editor', $bibTexItem)) {
159
                    $bibTexData['editor'] = $this->splitPersons($bibTexItem['editor']);
160
                }
161
162
                /** @var BibTexMetadata $bibTexMetadata */
163
                $bibTexMetadata = $this->objectManager->get(BibTexMetadata::class);
164
165
                $bibTexMetadata->setSource(get_class($this));
166
                $bibTexMetadata->setFeUser($this->security->getUser()->getUid());
167
                $bibTexMetadata->setData($encoder->encode($bibTexData, 'xml'));
168
169
                $results[] = $bibTexMetadata;
170
            }
171
172
        }
173
174
        $this->mandatoryErrors = $mandatoryErrors;
175
176
        return $results;
177
    }
178
179
    /**
180
     * @return array
181
     */
182
    public function getMandatoryErrors()
183
    {
184
        return $this->mandatoryErrors;
185
    }
186
187
    /**
188
     * @return bool
189
     */
190
    public function hasMandatoryErrors()
191
    {
192
        return !empty($this->mandatoryErrors);
193
    }
194
195
    /**
196
     * @return \EWW\Dpf\Domain\Model\TransformationFile|void
197
     */
198
    protected function getDefaultXsltTransformation()
199
    {
200
        /** @var \EWW\Dpf\Domain\Model\Client $client */
201
        $client = $this->clientRepository->findAll()->current();
202
203
        /** @var \EWW\Dpf\Domain\Model\TransformationFile $xsltTransformationFile */
204
        return $client->getBibTexTransformation()->current();
205
    }
206
207
    /**
208
     * @return string|void
209
     */
210
    protected function getDefaultXsltFilePath()
211
    {
212
        return \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName(
213
            'EXT:dpf/Resources/Private/Xslt/bibtex-default.xsl'
214
        );
215
    }
216
217
    /**
218
     * @return string|void
219
     */
220
    protected function getImporterName()
221
    {
222
        return 'bibtex';
223
    }
224
225
    /**
226
     * @param string $persons
227
     */
228
    protected function splitPersons($persons)
229
    {
230
        $results = [];
231
232
        $persons = array_map('trim', explode(' and ', $persons));
233
234
        foreach ($persons as $person) {
235
            list($family, $given) = array_map('trim', explode(',', $person));
236
            $results[] = [
237
                'family' => $family,
238
                'given' => $given
239
            ];
240
        }
241
242
        return $results;
243
    }
244
245
}