Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 94160c...0ee4f1 )
by
unknown
03:52 queued 14s
created

MetadataController::printMetadata()   D

Complexity

Conditions 52
Paths 116

Size

Total Lines 152
Code Lines 98

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 52
eloc 98
c 7
b 0
f 0
nc 116
nop 2
dl 0
loc 152
rs 4.0333

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
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace Kitodo\Dlf\Controller;
13
14
use Kitodo\Dlf\Common\Doc;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\IiifManifest;
17
use Kitodo\Dlf\Domain\Model\Collection;
18
use Kitodo\Dlf\Domain\Model\Metadata;
19
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
20
use Kitodo\Dlf\Domain\Repository\MetadataRepository;
21
use Kitodo\Dlf\Domain\Repository\StructureRepository;
22
use Ubl\Iiif\Context\IRI;
23
24
/**
25
 * Controller class for the plugin 'Metadata'.
26
 *
27
 * @author Sebastian Meyer <[email protected]>
28
 * @package TYPO3
29
 * @subpackage dlf
30
 * @access public
31
 */
32
class MetadataController extends AbstractController
33
{
34
    /**
35
     * @var CollectionRepository
36
     */
37
    protected $collectionRepository;
38
39
    /**
40
     * @param CollectionRepository $collectionRepository
41
     */
42
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
43
    {
44
        $this->collectionRepository = $collectionRepository;
45
    }
46
47
    /**
48
     * @var MetadataRepository
49
     */
50
    protected $metadataRepository;
51
52
    /**
53
     * @param MetadataRepository $metadataRepository
54
     */
55
    public function injectMetadataRepository(MetadataRepository $metadataRepository)
56
    {
57
        $this->metadataRepository = $metadataRepository;
58
    }
59
60
    /**
61
     * @var StructureRepository
62
     */
63
    protected $structureRepository;
64
65
    /**
66
     * @param StructureRepository $structureRepository
67
     */
68
    public function injectStructureRepository(StructureRepository $structureRepository)
69
    {
70
        $this->structureRepository = $structureRepository;
71
    }
72
73
    /**
74
     * @return string|void
75
     */
76
    public function mainAction()
77
    {
78
        $this->cObj = $this->configurationManager->getContentObject();
0 ignored issues
show
Bug Best Practice introduced by
The property cObj does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
79
80
        // Load current document.
81
        $this->loadDocument($this->requestData);
82
        if ($this->isDocMissing()) {
83
            // Quit without doing anything if required variables are not set.
84
            return '';
85
        } else {
86
            // Set default values if not set.
87
            if (!isset($this->settings['rootline'])) {
88
                $this->settings['rootline'] = 0;
89
            }
90
            if (!isset($this->settings['originalIiifMetadata'])) {
91
                $this->settings['originalIiifMetadata'] = 0;
92
            }
93
            if (!isset($this->settings['displayIiifDescription'])) {
94
                $this->settings['displayIiifDescription'] = 1;
95
            }
96
            if (!isset($this->settings['displayIiifRights'])) {
97
                $this->settings['displayIiifRights'] = 1;
98
            }
99
            if (!isset($this->settings['displayIiifLinks'])) {
100
                $this->settings['displayIiifLinks'] = 1;
101
            }
102
        }
103
        $useOriginalIiifManifestMetadata = $this->settings['originalIiifMetadata'] == 1 && $this->document->getDoc() instanceof IiifManifest;
104
        $metadata = $this->getMetadata();
105
        // Get titledata?
106
        if (empty($metadata) || ($this->settings['rootline'] == 1 && $metadata[0]['_id'] != $this->document->getDoc()->toplevelId)) {
107
            $data = $useOriginalIiifManifestMetadata ? $this->document->getDoc()->getManifestMetadata($this->document->getDoc()->toplevelId, $this->settings['storagePid']) : $this->document->getDoc()->getTitledata($this->settings['storagePid']);
108
            $data['_id'] = $this->document->getDoc()->toplevelId;
109
            array_unshift($metadata, $data);
110
        }
111
        if (empty($metadata)) {
112
            $this->logger->warning('No metadata found for document with UID ' . $this->document->getUid());
113
            return '';
114
        }
115
        ksort($metadata);
116
117
        $this->printMetadata($metadata, $useOriginalIiifManifestMetadata);
118
    }
119
120
    /**
121
     * Prepares the metadata array for output
122
     *
123
     * @access protected
124
     *
125
     * @param array $metadata: The metadata array
126
     * @param bool $useOriginalIiifManifestMetadata: Output IIIF metadata as simple key/value pairs?
127
     *
128
     * @return string The metadata array ready for output
129
     */
130
    protected function printMetadata(array $metadata, $useOriginalIiifManifestMetadata = false)
131
    {
132
        if ($useOriginalIiifManifestMetadata) {
133
            $iiifData = [];
134
            foreach ($metadata as $row) {
135
                foreach ($row as $key => $group) {
136
                    if ($key == '_id') {
137
                        continue;
138
                    }
139
                    if (!is_array($group)) {
140
                        if (
141
                            IRI::isAbsoluteIri($group)
142
                            && (($scheme = (new IRI($group))->getScheme()) == 'http' || $scheme == 'https')
143
                        ) {
144
                            // Build link
145
                            $iiifData[$key] = [
146
                                'label' => $key,
147
                                'value' => $group,
148
                                'buildUrl' => true,
149
                            ];
150
                        } else {
151
                            // Data output
152
                            $iiifData[$key] = [
153
                                'label' => $key,
154
                                'value' => $group,
155
                                'buildUrl' => false,
156
                            ];
157
                        }
158
                    } else {
159
                        foreach ($group as $label => $value) {
160
                            if ($label == '_id') {
161
                                continue;
162
                            }
163
                            if (is_array($value)) {
164
                                $value = implode($this->settings['separator'], $value);
165
                            }
166
                            // NOTE: Labels are to be escaped in Fluid template
167
                            if (IRI::isAbsoluteIri($value) && (($scheme = (new IRI($value))->getScheme()) == 'http' || $scheme == 'https')) {
168
                                $nolabel = $value == $label;
169
                                $iiifData[$key]['data'][] = [
170
                                    'label' => $nolabel ? '' : $label,
171
                                    'value' => $value,
172
                                    'buildUrl' => true,
173
                                ];
174
                            } else {
175
                                $iiifData[$key]['data'][] = [
176
                                    'label' => $label,
177
                                    'value' => $value,
178
                                    'buildUrl' => false,
179
                                ];
180
                            }
181
                        }
182
                    }
183
                    $this->view->assign('useIiif', true);
184
                    $this->view->assign('iiifData', $iiifData);
185
                }
186
            }
187
        } else {
188
            // findBySettings also sorts entries by the `sorting` field
189
            $metadataResult = $this->metadataRepository->findBySettings([
190
                'is_listed' => !$this->settings['showFull'],
191
            ]);
192
193
            // Collect raw metadata into an array that will be passed as data to cObj.
194
            // This lets metadata wraps reference (own or foreign) values via TypoScript "field".
195
            $metaCObjData = [];
196
197
            $buildUrl = [];
198
            $externalUrl = [];
199
            $i = 0;
200
            foreach ($metadata as $section) {
201
                $metaCObjData[$i] = [];
202
203
                foreach ($section as $name => $value) {
204
                    // NOTE: Labels are to be escaped in Fluid template
205
206
                    $metaCObjData[$i][$name] = is_array($value)
207
                        ? implode($this->settings['separator'], $value)
208
                        : $value;
209
210
                    if ($name == 'title') {
211
                        // Get title of parent document if needed.
212
                        if (empty(implode('', $value)) && $this->settings['getTitle'] && $this->document->getPartof()) {
213
                            $superiorTitle = Doc::getTitle($this->document->getPartof(), true);
214
                            if (!empty($superiorTitle)) {
215
                                $metadata[$i][$name] = ['[' . $superiorTitle . ']'];
216
                            }
217
                        }
218
                        if (!empty($value)) {
219
                            $metadata[$i][$name][0] = $metadata[$i][$name][0];
220
                            // Link title to pageview.
221
                            if ($this->settings['linkTitle'] && $section['_id']) {
222
                                $details = $this->document->getDoc()->getLogicalStructure($section['_id']);
223
                                $buildUrl[$i][$name]['buildUrl'] = [
224
                                    'id' => $this->document->getUid(),
225
                                    'page' => (!empty($details['points']) ? intval($details['points']) : 1),
226
                                    'targetPid' => (!empty($this->settings['targetPid']) ? $this->settings['targetPid'] : 0),
227
                                ];
228
                            }
229
                        }
230
                    } elseif (($name == 'author' || $name == 'holder') && !empty($value) && !empty($value[0]['url'])) {
231
                        $externalUrl[$i][$name]['externalUrl'] = $value[0];
232
                    } elseif (($name == 'geonames' || $name == 'wikidata' || $name == 'wikipedia') && !empty($value)) {
233
                        $externalUrl[$i][$name]['externalUrl'] = [
234
                            'name' => $value[0],
235
                            'url' => $value[0]
236
                        ];
237
                    } elseif ($name == 'owner' && empty($value)) {
238
                        // no owner is found by metadata records --> take the one associated to the document
239
                        $library = $this->document->getOwner();
240
                        if ($library) {
241
                            $metadata[$i][$name][0] = $library->getLabel();
242
                        }
243
                    } elseif ($name == 'type' && !empty($value)) {
244
                        // Translate document type.
245
                        $structure = $this->structureRepository->findOneByIndexName($metadata[$i][$name][0]);
0 ignored issues
show
Bug introduced by
The method findOneByIndexName() does not exist on Kitodo\Dlf\Domain\Repository\StructureRepository. 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

245
                        /** @scrutinizer ignore-call */ 
246
                        $structure = $this->structureRepository->findOneByIndexName($metadata[$i][$name][0]);
Loading history...
246
                        if ($structure) {
247
                            $metadata[$i][$name][0] = $structure->getLabel();
0 ignored issues
show
Bug introduced by
The method getLabel() 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

247
                            /** @scrutinizer ignore-call */ 
248
                            $metadata[$i][$name][0] = $structure->getLabel();

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...
248
                        }
249
                    } elseif ($name == 'collection' && !empty($value)) {
250
                        // Check if collections isn't hidden.
251
                        $j = 0;
252
                        foreach ($value as $entry) {
253
                            $collection = $this->collectionRepository->findOneByIndexName($entry);
0 ignored issues
show
Bug introduced by
The method findOneByIndexName() does not exist on Kitodo\Dlf\Domain\Repository\CollectionRepository. 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

253
                            /** @scrutinizer ignore-call */ 
254
                            $collection = $this->collectionRepository->findOneByIndexName($entry);
Loading history...
254
                            if ($collection) {
255
                                $metadata[$i][$name][$j] = $collection->getLabel() ? : '';
256
                                $j++;
257
                            }
258
                        }
259
                    } elseif ($name == 'language' && !empty($value)) {
260
                        // Translate ISO 639 language code.
261
                        foreach ($metadata[$i][$name] as &$langValue) {
262
                            $langValue = Helper::getLanguageName($langValue);
263
                        }
264
                    }
265
266
                    if (is_array($metadata[$i][$name])) {
267
                        $metadata[$i][$name] = array_values(array_filter($metadata[$i][$name], function($metadataValue)
268
                        {
269
                            return !empty($metadataValue);
270
                        }));
271
                    }
272
                }
273
                $i++;
274
            }
275
276
            $this->view->assign('buildUrl', $buildUrl);
277
            $this->view->assign('externalUrl', $externalUrl);
278
            $this->view->assign('documentMetadataSections', $metadata);
279
            $this->view->assign('configMetadata', $metadataResult);
280
            $this->view->assign('separator', $this->settings['separator']);
281
            $this->view->assign('metaCObjData', $metaCObjData);
282
        }
283
    }
284
285
    /**
286
     * Get metadata for given id array.
287
     *
288
     * @access private
289
     *
290
     * @return array metadata
291
     */
292
    private function getMetadata()
293
    {
294
        $metadata = [];
295
        if ($this->settings['rootline'] < 2) {
296
            // Get current structure's @ID.
297
            $ids = [];
298
            if (!empty($this->document->getDoc()->physicalStructure[$this->requestData['page']]) && !empty($this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page']]])) {
299
                foreach ($this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page']]] as $logId) {
300
                    $count = $this->document->getDoc()->getStructureDepth($logId);
301
                    $ids[$count][] = $logId;
302
                }
303
            }
304
            ksort($ids);
305
            reset($ids);
306
            // Check if we should display all metadata up to the root.
307
            if ($this->settings['rootline'] == 1) {
308
                foreach ($ids as $id) {
309
                    $metadata = $this->getMetadataForIds($id, $metadata);
310
                }
311
            } else {
312
                $id = array_pop($ids);
313
                if (is_array($id)) {
314
                    $metadata = $this->getMetadataForIds($id, $metadata);
315
                }
316
            }
317
        }
318
        return $metadata;
319
    }
320
321
    /**
322
     * Get metadata for given id array.
323
     *
324
     * @access private
325
     *
326
     * @param array $id: An array with ids
327
     * @param array $metadata: An array with metadata
328
     *
329
     * @return array metadata
330
     */
331
    private function getMetadataForIds($id, $metadata)
332
    {
333
        $useOriginalIiifManifestMetadata = $this->settings['originalIiifMetadata'] == 1 && $this->document->getDoc() instanceof IiifManifest;
334
        foreach ($id as $sid) {
335
            if ($useOriginalIiifManifestMetadata) {
336
                $data = $this->document->getDoc()->getManifestMetadata($sid, $this->settings['storagePid']);
337
            } else {
338
                $data = $this->document->getDoc()->getMetadata($sid, $this->settings['storagePid']);
339
            }
340
            if (!empty($data)) {
341
                $data['_id'] = $sid;
342
                $metadata[] = $data;
343
            }
344
        }
345
        return $metadata;
346
    }
347
}
348