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
03:37
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 (
83
            $this->document === null
84
            || $this->document->getDoc() === null
85
        ) {
86
            // Quit without doing anything if required variables are not set.
87
            return '';
88
        } else {
89
            // Set default values if not set.
90
            if (!isset($this->settings['rootline'])) {
91
                $this->settings['rootline'] = 0;
92
            }
93
            if (!isset($this->settings['originalIiifMetadata'])) {
94
                $this->settings['originalIiifMetadata'] = 0;
95
            }
96
            if (!isset($this->settings['displayIiifDescription'])) {
97
                $this->settings['displayIiifDescription'] = 1;
98
            }
99
            if (!isset($this->settings['displayIiifRights'])) {
100
                $this->settings['displayIiifRights'] = 1;
101
            }
102
            if (!isset($this->settings['displayIiifLinks'])) {
103
                $this->settings['displayIiifLinks'] = 1;
104
            }
105
        }
106
        $useOriginalIiifManifestMetadata = $this->settings['originalIiifMetadata'] == 1 && $this->document->getDoc() instanceof IiifManifest;
107
        $metadata = $this->getMetadata();
108
        // Get titledata?
109
        if (empty($metadata) || ($this->settings['rootline'] == 1 && $metadata[0]['_id'] != $this->document->getDoc()->toplevelId)) {
110
            $data = $useOriginalIiifManifestMetadata ? $this->document->getDoc()->getManifestMetadata($this->document->getDoc()->toplevelId, $this->settings['storagePid']) : $this->document->getDoc()->getTitledata($this->settings['storagePid']);
111
            $data['_id'] = $this->document->getDoc()->toplevelId;
112
            $data['_active'] = true;
113
            array_unshift($metadata, $data);
114
        }
115
        if (empty($metadata)) {
116
            $this->logger->warning('No metadata found for document with UID ' . $this->document->getUid());
117
            return '';
118
        }
119
        ksort($metadata);
120
121
        $this->printMetadata($metadata, $useOriginalIiifManifestMetadata);
122
    }
123
124
    /**
125
     * Prepares the metadata array for output
126
     *
127
     * @access protected
128
     *
129
     * @param array $metadataArray: The metadata array
130
     * @param bool $useOriginalIiifManifestMetadata: Output IIIF metadata as simple key/value pairs?
131
     *
132
     * @return string The metadata array ready for output
133
     */
134
    protected function printMetadata(array $metadataArray, $useOriginalIiifManifestMetadata = false)
135
    {
136
        if ($useOriginalIiifManifestMetadata) {
137
            $iiifData = [];
138
            foreach ($metadataArray as $metadata) {
139
                foreach ($metadata as $key => $group) {
140
                    if ($key == '_id' || $key === '_active') {
141
                        continue;
142
                    }
143
                    if (!is_array($group)) {
144
                        if (
145
                            IRI::isAbsoluteIri($group)
146
                            && (($scheme = (new IRI($group))->getScheme()) == 'http' || $scheme == 'https')
147
                        ) {
148
                            // Build link
149
                            $iiifData[$key] = [
150
                                'label' => $key,
151
                                'value' => $group,
152
                                'buildUrl' => true,
153
                            ];
154
                        } else {
155
                            // Data output
156
                            $iiifData[$key] = [
157
                                'label' => $key,
158
                                'value' => $group,
159
                                'buildUrl' => false,
160
                            ];
161
                        }
162
                    } else {
163
                        foreach ($group as $label => $value) {
164
                            if ($label === '_id' || $label === '_active') {
165
                                continue;
166
                            }
167
                            if (is_array($value)) {
168
                                $value = implode($this->settings['separator'], $value);
169
                            }
170
                            // NOTE: Labels are to be escaped in Fluid template
171
                            if (IRI::isAbsoluteIri($value) && (($scheme = (new IRI($value))->getScheme()) == 'http' || $scheme == 'https')) {
172
                                $nolabel = $value == $label;
173
                                $iiifData[$key]['data'][] = [
174
                                    'label' => $nolabel ? '' : $label,
175
                                    'value' => $value,
176
                                    'buildUrl' => true,
177
                                ];
178
                            } else {
179
                                $iiifData[$key]['data'][] = [
180
                                    'label' => $label,
181
                                    'value' => $value,
182
                                    'buildUrl' => false,
183
                                ];
184
                            }
185
                        }
186
                    }
187
                    $this->view->assign('useIiif', true);
188
                    $this->view->assign('iiifData', $iiifData);
189
                }
190
            }
191
        } else {
192
193
            // findBySettings also sorts entries by the `sorting` field
194
            $metadataResult = $this->metadataRepository->findBySettings([
195
                'is_listed' => !$this->settings['showFull'],
196
            ]);
197
198
            // Collect raw metadata into an array that will be passed as data to cObj.
199
            // This lets metadata wraps reference (own or foreign) values via TypoScript "field".
200
            $metaCObjData = [];
201
202
            $buildUrl = [];
203
            $i = 0;
204
            foreach ($metadataArray as $metadataSection) {
205
                $metaCObjData[$i] = [];
206
207
                foreach ($metadataSection as $metadataName => $metadataValue) {
208
                    // NOTE: Labels are to be escaped in Fluid template
209
210
                    $metaCObjData[$i][$metadataName] = is_array($metadataValue)
211
                        ? implode($this->settings['separator'], $metadataValue)
212
                        : $metadataValue;
213
214
                    if ($metadataName == 'title') {
215
                        // Get title of parent document if needed.
216
                        if (empty(implode('', $metadataValue)) && $this->settings['getTitle'] && $this->document->getPartof()) {
217
                            $superiorTitle = Doc::getTitle($this->document->getPartof(), true);
218
                            if (!empty($superiorTitle)) {
219
                                $metadataArray[$i][$metadataName] = ['[' . $superiorTitle . ']'];
220
                            }
221
                        }
222
                        if (!empty($metadataValue)) {
223
                            $metadataArray[$i][$metadataName][0] = $metadataArray[$i][$metadataName][0];
224
                            // Link title to pageview.
225
                            if ($this->settings['linkTitle'] && $metadataSection['_id']) {
226
                                $details = $this->document->getDoc()->getLogicalStructure($metadataSection['_id']);
227
                                $buildUrl[$i][$metadataName]['buildUrl'] = [
228
                                    'id' => $this->document->getUid(),
229
                                    'page' => (!empty($details['points']) ? intval($details['points']) : 1),
230
                                    'targetPid' => (!empty($this->settings['targetPid']) ? $this->settings['targetPid'] : 0),
231
                                ];
232
                            }
233
                        }
234
                    } elseif ($metadataName == 'owner' && empty($metadataValue)) {
235
                        // no owner is found by metadata records --> take the one associated to the document
236
                        $library = $this->document->getOwner();
237
                        if ($library) {
238
                            $metadataArray[$i][$metadataName][0] = $library->getLabel();
239
                        }
240
                    } elseif ($metadataName == 'type' && !empty($metadataValue)) {
241
                        // Translate document type.
242
                        $structure = $this->structureRepository->findOneByIndexName($metadataArray[$i][$metadataName][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

242
                        /** @scrutinizer ignore-call */ 
243
                        $structure = $this->structureRepository->findOneByIndexName($metadataArray[$i][$metadataName][0]);
Loading history...
243
                        if ($structure) {
244
                            $metadataArray[$i][$metadataName][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

244
                            /** @scrutinizer ignore-call */ 
245
                            $metadataArray[$i][$metadataName][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...
245
                        }
246
                    } elseif ($metadataName == 'collection' && !empty($metadataValue)) {
247
                        // Check if collections isn't hidden.
248
                        $j = 0;
249
                        foreach ($metadataValue as $metadataEntry) {
250
                            $collection = $this->collectionRepository->findOneByIndexName($metadataEntry);
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

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