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
Pull Request — master (#878)
by Beatrycze
11:59 queued 06:25
created

getIds()   A

Complexity

Conditions 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
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
            $data['_active'] = true;
110
            array_unshift($metadata, $data);
111
        }
112
        if (empty($metadata)) {
113
            $this->logger->warning('No metadata found for document with UID ' . $this->document->getUid());
114
            return '';
115
        }
116
        ksort($metadata);
117
118
        $this->printMetadata($metadata, $useOriginalIiifManifestMetadata);
119
    }
120
121
    /**
122
     * Prepares the metadata array for output
123
     *
124
     * @access protected
125
     *
126
     * @param array $metadata: The metadata array
127
     * @param bool $useOriginalIiifManifestMetadata: Output IIIF metadata as simple key/value pairs?
128
     *
129
     * @return string The metadata array ready for output
130
     */
131
    protected function printMetadata(array $metadata, $useOriginalIiifManifestMetadata = false)
132
    {
133
        if ($useOriginalIiifManifestMetadata) {
134
            $iiifData = [];
135
            foreach ($metadata as $row) {
136
                foreach ($row as $key => $group) {
137
                    if ($key == '_id' || $key === '_active') {
138
                        continue;
139
                    }
140
                    if (!is_array($group)) {
141
                        if (
142
                            IRI::isAbsoluteIri($group)
143
                            && (($scheme = (new IRI($group))->getScheme()) == 'http' || $scheme == 'https')
144
                        ) {
145
                            // Build link
146
                            $iiifData[$key] = [
147
                                'label' => $key,
148
                                'value' => $group,
149
                                'buildUrl' => true,
150
                            ];
151
                        } else {
152
                            // Data output
153
                            $iiifData[$key] = [
154
                                'label' => $key,
155
                                'value' => $group,
156
                                'buildUrl' => false,
157
                            ];
158
                        }
159
                    } else {
160
                        foreach ($group as $label => $value) {
161
                            if ($label === '_id' || $label === '_active') {
162
                                continue;
163
                            }
164
                            if (is_array($value)) {
165
                                $value = implode($this->settings['separator'], $value);
166
                            }
167
                            // NOTE: Labels are to be escaped in Fluid template
168
                            if (IRI::isAbsoluteIri($value) && (($scheme = (new IRI($value))->getScheme()) == 'http' || $scheme == 'https')) {
169
                                $nolabel = $value == $label;
170
                                $iiifData[$key]['data'][] = [
171
                                    'label' => $nolabel ? '' : $label,
172
                                    'value' => $value,
173
                                    'buildUrl' => true,
174
                                ];
175
                            } else {
176
                                $iiifData[$key]['data'][] = [
177
                                    'label' => $label,
178
                                    'value' => $value,
179
                                    'buildUrl' => false,
180
                                ];
181
                            }
182
                        }
183
                    }
184
                    $this->view->assign('useIiif', true);
185
                    $this->view->assign('iiifData', $iiifData);
186
                }
187
            }
188
        } else {
189
            // findBySettings also sorts entries by the `sorting` field
190
            $metadataResult = $this->metadataRepository->findBySettings([
191
                'is_listed' => !$this->settings['showFull'],
192
            ]);
193
194
            // Collect raw metadata into an array that will be passed as data to cObj.
195
            // This lets metadata wraps reference (own or foreign) values via TypoScript "field".
196
            $metaCObjData = [];
197
198
            $buildUrl = [];
199
            $externalUrl = [];
200
            $i = 0;
201
            foreach ($metadata as $section) {
202
                $metaCObjData[$i] = [];
203
204
                foreach ($section as $name => $value) {
205
                    // NOTE: Labels are to be escaped in Fluid template
206
207
                    $metaCObjData[$i][$name] = is_array($value)
208
                        ? implode($this->settings['separator'], $value)
209
                        : $value;
210
211
                    if ($name == 'title') {
212
                        // Get title of parent document if needed.
213
                        if (empty(implode('', $value)) && $this->settings['getTitle'] && $this->document->getPartof()) {
214
                            $superiorTitle = Doc::getTitle($this->document->getPartof(), true);
215
                            if (!empty($superiorTitle)) {
216
                                $metadata[$i][$name] = ['[' . $superiorTitle . ']'];
217
                            }
218
                        }
219
                        if (!empty($value)) {
220
                            $metadata[$i][$name][0] = $metadata[$i][$name][0];
221
                            // Link title to pageview.
222
                            if ($this->settings['linkTitle'] && $section['_id']) {
223
                                $details = $this->document->getDoc()->getLogicalStructure($section['_id']);
224
                                $buildUrl[$i][$name]['buildUrl'] = [
225
                                    'id' => $this->document->getUid(),
226
                                    'page' => (!empty($details['points']) ? intval($details['points']) : 1),
227
                                    'targetPid' => (!empty($this->settings['targetPid']) ? $this->settings['targetPid'] : 0),
228
                                ];
229
                            }
230
                        }
231
                    } elseif (($name == 'author' || $name == 'holder') && !empty($value) && !empty($value[0]['url'])) {
232
                        $externalUrl[$i][$name]['externalUrl'] = $value[0];
233
                    } elseif (($name == 'geonames' || $name == 'wikidata' || $name == 'wikipedia') && !empty($value)) {
234
                        $externalUrl[$i][$name]['externalUrl'] = [
235
                            'name' => $value[0],
236
                            'url' => $value[0]
237
                        ];
238
                    } elseif ($name == 'owner' && empty($value)) {
239
                        // no owner is found by metadata records --> take the one associated to the document
240
                        $library = $this->document->getOwner();
241
                        if ($library) {
242
                            $metadata[$i][$name][0] = $library->getLabel();
243
                        }
244
                    } elseif ($name == 'type' && !empty($value)) {
245
                        // Translate document type.
246
                        $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

246
                        /** @scrutinizer ignore-call */ 
247
                        $structure = $this->structureRepository->findOneByIndexName($metadata[$i][$name][0]);
Loading history...
247
                        if ($structure) {
248
                            $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

248
                            /** @scrutinizer ignore-call */ 
249
                            $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...
249
                        }
250
                    } elseif ($name == 'collection' && !empty($value)) {
251
                        // Check if collections isn't hidden.
252
                        $j = 0;
253
                        foreach ($value as $entry) {
254
                            $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

254
                            /** @scrutinizer ignore-call */ 
255
                            $collection = $this->collectionRepository->findOneByIndexName($entry);
Loading history...
255
                            if ($collection) {
256
                                $metadata[$i][$name][$j] = $collection->getLabel() ? : '';
257
                                $j++;
258
                            }
259
                        }
260
                    } elseif ($name == 'language' && !empty($value)) {
261
                        // Translate ISO 639 language code.
262
                        foreach ($metadata[$i][$name] as &$langValue) {
263
                            $langValue = Helper::getLanguageName($langValue);
264
                        }
265
                    } elseif (!empty($value)) {
266
                        $metadata[$i][$name][0] = $metadata[$i][$name][0];
267
                    }
268
269
                    if (is_array($metadata[$i][$name])) {
270
                        $metadata[$i][$name] = array_values(array_filter($metadata[$i][$name], function($metadataValue)
271
                        {
272
                            return !empty($metadataValue);
273
                        }));
274
                    }
275
                }
276
                $i++;
277
            }
278
279
            $this->view->assign('buildUrl', $buildUrl);
280
            $this->view->assign('externalUrl', $externalUrl);
281
            $this->view->assign('documentMetadataSections', $metadata);
282
            $this->view->assign('configMetadata', $metadataResult);
283
            $this->view->assign('separator', $this->settings['separator']);
284
            $this->view->assign('metaCObjData', $metaCObjData);
285
        }
286
    }
287
288
    /**
289
     * Get metadata for given id array.
290
     *
291
     * @access private
292
     *
293
     * @return array metadata
294
     */
295
    private function getMetadata()
296
    {
297
        $metadata = [];
298
        if ($this->settings['rootline'] < 2) {
299
            // Get current structure's @ID.
300
            $ids = $this->document->getDoc()->getLogicalSectionsOnPage((int) $this->requestData['page']);
301
302
            // Check if we should display all metadata up to the root.
303
            if ($this->settings['prerenderAllSections'] ?? false) {
304
                // Collect IDs of all logical structures. This is a flattened tree, so the
305
                // order also works for rootline configurations.
306
                $allIds = [];
307
                function getIds($toc, &$output) {
308
                    foreach ($toc as $entry) {
309
                        $output[$entry['id']] = true;
310
                        if (is_array($entry['children'])) {
311
                            getIds($entry['children'], $output);
312
                        }
313
                    }
314
                }
315
                getIds($this->document->getDoc()->tableOfContents, $allIds);
316
317
                $idIsActive = [];
318
                foreach ($ids as $id) {
319
                    foreach ($id as $sid) {
320
                        $idIsActive[$sid] = true;
321
                    }
322
                }
323
324
                $metadata = $this->getMetadataForIds(array_keys($allIds), $metadata);
325
                foreach ($metadata as &$entry) {
326
                    $entry['_active'] = isset($idIsActive[$entry['_id']]);
327
                }
328
            } elseif ($this->settings['rootline'] == 1) {
329
                foreach ($ids as $id) {
330
                    $metadata = $this->getMetadataForIds($id, $metadata);
331
                }
332
            } else {
333
                $id = array_pop($ids);
334
                if (is_array($id)) {
335
                    $metadata = $this->getMetadataForIds($id, $metadata);
336
                }
337
            }
338
        }
339
        return $metadata;
340
    }
341
342
    /**
343
     * Get metadata for given id array.
344
     *
345
     * @access private
346
     *
347
     * @param array $id: An array with ids
348
     * @param array $metadata: An array with metadata
349
     *
350
     * @return array metadata
351
     */
352
    private function getMetadataForIds($id, $metadata)
353
    {
354
        $useOriginalIiifManifestMetadata = $this->settings['originalIiifMetadata'] == 1 && $this->document->getDoc() instanceof IiifManifest;
355
        foreach ($id as $sid) {
356
            if ($useOriginalIiifManifestMetadata) {
357
                $data = $this->document->getDoc()->getManifestMetadata($sid, $this->settings['storagePid']);
358
            } else {
359
                $data = $this->document->getDoc()->getMetadata($sid, $this->settings['storagePid']);
360
            }
361
            if (!empty($data)) {
362
                $data['_id'] = $sid;
363
                $data['_active'] = true;
364
                $metadata[] = $data;
365
            }
366
        }
367
        return $metadata;
368
    }
369
}
370