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 (#837)
by Beatrycze
03:29
created

TableOfContentsController::getMenuEntry()   D

Complexity

Conditions 19
Paths 140

Size

Total Lines 83
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 19
eloc 53
c 2
b 0
f 0
nc 140
nop 2
dl 0
loc 83
rs 4.1833

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\Helper;
15
use Kitodo\Dlf\Common\MetsDocument;
16
use TYPO3\CMS\Core\Utility\MathUtility;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19
/**
20
 * Controller class for plugin 'Table Of Contents'.
21
 *
22
 * @author Sebastian Meyer <[email protected]>
23
 * @package TYPO3
24
 * @subpackage dlf
25
 * @access public
26
 */
27
class TableOfContentsController extends AbstractController
28
{
29
    /**
30
     * This holds the active entries according to the currently selected page
31
     *
32
     * @var array
33
     * @access protected
34
     */
35
    protected $activeEntries = [];
36
37
    /**
38
     * This holds the list of authors for autocomplete
39
     *
40
     * @var array
41
     * @access protected
42
     */
43
    protected $authors = [];
44
45
    /**
46
     * This holds the list of titles for autocomplete
47
     *
48
     * @var array
49
     * @access protected
50
     */
51
    protected $titles = [];
52
53
    /**
54
     * The main method of the plugin
55
     *
56
     * @return void
57
     */
58
    public function mainAction()
59
    {
60
        // Load current document.
61
        $this->loadDocument($this->requestData);
62
        if (
63
            $this->document === null
64
            || $this->document->getDoc() === null
65
        ) {
66
            // Quit without doing anything if required variables are not set.
67
            return;
68
        } else {
69
            if (!empty($this->requestData['logicalPage'])) {
70
                $this->requestData['page'] = $this->document->getDoc()->getPhysicalPage($this->requestData['logicalPage']);
71
                // The logical page parameter should not appear again
72
                unset($this->requestData['logicalPage']);
73
            }
74
            if ($this->document->getDoc()->tableOfContents[0]['type'] == 'collection') {
75
                $this->view->assign('currentList', $this->requestData['id']);
76
                if (isset($this->requestData['transform'])) {
77
                    $this->view->assign('transform', $this->requestData['transform']);
78
                } else {
79
                    $this->view->assign('transform', 'something');
80
                }
81
                $this->view->assign('type', 'collection');
82
                $this->view->assign('types', $this->getTypes($this->document->getDoc()->tableOfContents));
83
                $this->view->assign('toc', $this->makeMenuFor3DObjects());
84
                $this->view->assign('authors', $this->authors);
85
                $this->view->assign('titles', $this->titles);
86
            } else {
87
                $this->view->assign('type', 'other');
88
                $this->view->assign('toc', $this->makeMenuArray());
89
            }
90
        }
91
    }
92
93
    /**
94
     * This builds a menu array for HMENU
95
     *
96
     * @access protected
97
     * @return array HMENU array
98
     */
99
    protected function makeMenuArray()
100
    {
101
        // Set default values for page if not set.
102
        // $this->requestData['page'] may be integer or string (physical structure @ID)
103
        if (
104
            (int) $this->requestData['page'] > 0
105
            || empty($this->requestData['page'])
106
        ) {
107
            $this->requestData['page'] = MathUtility::forceIntegerInRange((int) $this->requestData['page'], 1, $this->document->getDoc()->numPages, 1);
108
        } else {
109
            $this->requestData['page'] = array_search($this->requestData['page'], $this->document->getDoc()->physicalStructure);
110
        }
111
        $this->requestData['double'] = MathUtility::forceIntegerInRange($this->requestData['double'], 0, 1, 0);
112
        $menuArray = [];
113
        // Does the document have physical elements or is it an external file?
114
        if (
115
            !empty($this->document->getDoc()->physicalStructure)
116
            || !MathUtility::canBeInterpretedAsInteger($this->requestData['id'])
117
        ) {
118
            // Get all logical units the current page or track is a part of.
119
            if (
120
                !empty($this->requestData['page'])
121
                && !empty($this->document->getDoc()->physicalStructure)
122
            ) {
123
                $this->activeEntries = array_merge((array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[0]],
124
                    (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page']]]);
125
                if (
126
                    !empty($this->requestData['double'])
127
                    && $this->requestData['page'] < $this->document->getDoc()->numPages
128
                ) {
129
                    $this->activeEntries = array_merge($this->activeEntries,
130
                        (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page'] + 1]]);
131
                }
132
            }
133
            // Go through table of contents and create all menu entries.
134
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
135
                $menuArray[] = $this->getMenuEntry($entry, true);
136
            }
137
        } else {
138
            // Go through table of contents and create top-level menu entries.
139
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
140
                $menuArray[] = $this->getMenuEntry($entry, false);
141
            }
142
            // Build table of contents from database.
143
            $result = $this->documentRepository->getTableOfContentsFromDb($this->document->getUid(), $this->document->getPid(), $this->settings);
144
145
            $allResults = $result->fetchAll();
0 ignored issues
show
Bug introduced by
The method fetchAll() 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

145
            /** @scrutinizer ignore-call */ 
146
            $allResults = $result->fetchAll();

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...
146
147
            if (count($allResults) > 0) {
148
                $menuArray[0]['ITEM_STATE'] = 'CURIFSUB';
149
                $menuArray[0]['_SUB_MENU'] = [];
150
                foreach ($allResults as $resArray) {
151
                    $entry = [
152
                        'label' => !empty($resArray['mets_label']) ? $resArray['mets_label'] : $resArray['title'],
153
                        'type' => $resArray['type'],
154
                        'volume' => $resArray['volume'],
155
                        'orderlabel' => $resArray['mets_orderlabel'],
156
                        'pagination' => '',
157
                        'targetUid' => $resArray['uid']
158
                    ];
159
                    $menuArray[0]['_SUB_MENU'][] = $this->getMenuEntry($entry, false);
160
                }
161
            }
162
        }
163
        return $menuArray;
164
    }
165
166
    /**
167
     * This builds a menu for list of 3D objects
168
     *
169
     * @access protected
170
     *
171
     * @param string $content: The PlugIn content
172
     * @param array $conf: The PlugIn configuration
173
     *
174
     * @return array HMENU array
175
     */
176
    protected function makeMenuFor3DObjects()
177
    {
178
        $menuArray = [];
179
        // Is the document an external file?
180
        if (!MathUtility::canBeInterpretedAsInteger($this->requestData['id'])) {
181
            // Go through table of contents and create all menu entries.
182
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
183
                $menuArray[] = $this->getMenuEntryWithImage($entry, true);
184
            }
185
        }
186
        return $menuArray;
187
    }
188
189
    /**
190
     * This builds an array for one menu entry
191
     *
192
     * @access protected
193
     *
194
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
195
     * @param bool $recursive : Whether to include the child entries
196
     *
197
     * @return array HMENU array for menu entry
198
     */
199
    protected function getMenuEntry(array $entry, $recursive = false)
200
    {
201
        $entry = $this->resolveMenuEntry($entry);
202
203
        $entryArray = [];
204
        // Set "title", "volume", "type" and "pagination" from $entry array.
205
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
206
        $entryArray['volume'] = $entry['volume'];
207
        $entryArray['orderlabel'] = $entry['orderlabel'];
208
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['storagePid']);
209
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
210
        $entryArray['_OVERRIDE_HREF'] = '';
211
        $entryArray['doNotLinkIt'] = 1;
212
        $entryArray['ITEM_STATE'] = 'NO';
213
        // Build menu links based on the $entry['points'] array.
214
        if (
215
            !empty($entry['points'])
216
            && MathUtility::canBeInterpretedAsInteger($entry['points'])
217
        ) {
218
            $entryArray['page'] = $entry['points'];
219
220
            $entryArray['doNotLinkIt'] = 0;
221
            if ($this->settings['basketButton']) {
222
                $entryArray['basketButton'] = [
223
                    'logId' => $entry['id'],
224
                    'startpage' => $entry['points']
225
                ];
226
            }
227
        } elseif (
228
            !empty($entry['points'])
229
            && is_string($entry['points'])
230
        ) {
231
            $entryArray['id'] = $entry['points'];
232
            $entryArray['page'] = 1;
233
            $entryArray['doNotLinkIt'] = 0;
234
            if ($this->settings['basketButton']) {
235
                $entryArray['basketButton'] = [
236
                    'logId' => $entry['id'],
237
                    'startpage' => $entry['points']
238
                ];
239
            }
240
        } elseif (!empty($entry['targetUid'])) {
241
            $entryArray['id'] = $entry['targetUid'];
242
            $entryArray['page'] = 1;
243
            $entryArray['doNotLinkIt'] = 0;
244
            if ($this->settings['basketButton']) {
245
                $entryArray['basketButton'] = [
246
                    'logId' => $entry['id'],
247
                    'startpage' => $entry['targetUid']
248
                ];
249
            }
250
        }
251
        // Set "ITEM_STATE" to "CUR" if this entry points to current page.
252
        if (in_array($entry['id'], $this->activeEntries)) {
253
            $entryArray['ITEM_STATE'] = 'CUR';
254
        }
255
        // Build sub-menu if available and called recursively.
256
        if (
257
            $recursive === true
258
            && !empty($entry['children'])
259
        ) {
260
            // Build sub-menu only if one of the following conditions apply:
261
            // 1. Current menu node is in rootline
262
            // 2. Current menu node points to another file
263
            // 3. Current menu node has no corresponding images
264
            if (
265
                $entryArray['ITEM_STATE'] == 'CUR'
266
                || is_string($entry['points'])
267
                || empty($this->document->getDoc()->smLinks['l2p'][$entry['id']])
268
            ) {
269
                $entryArray['_SUB_MENU'] = [];
270
                foreach ($entry['children'] as $child) {
271
                    // Set "ITEM_STATE" to "ACT" if this entry points to current page and has sub-entries pointing to the same page.
272
                    if (in_array($child['id'], $this->activeEntries)) {
273
                        $entryArray['ITEM_STATE'] = 'ACT';
274
                    }
275
                    $entryArray['_SUB_MENU'][] = $this->getMenuEntry($child, true);
276
                }
277
            }
278
            // Append "IFSUB" to "ITEM_STATE" if this entry has sub-entries.
279
            $entryArray['ITEM_STATE'] = ($entryArray['ITEM_STATE'] == 'NO' ? 'IFSUB' : $entryArray['ITEM_STATE'] . 'IFSUB');
280
        }
281
        return $entryArray;
282
    }
283
284
    /**
285
     * If $entry references an external METS file (as mptr),
286
     * try to resolve its database UID and return an updated $entry.
287
     *
288
     * This is so that when linking from a child document back to its parent,
289
     * that link is via UID, so that subsequently the parent's TOC is built from database.
290
     *
291
     * @param array $entry
292
     * @return array
293
     */
294
    protected function resolveMenuEntry($entry)
295
    {
296
        // If the menu entry points to the parent document,
297
        // resolve to the parent UID set on indexation.
298
        $doc = $this->document->getDoc();
299
        if (
300
            $doc instanceof MetsDocument
301
            && $entry['points'] === $doc->parentHref
302
            && !empty($this->document->getPartof())
303
        ) {
304
            unset($entry['points']);
305
            $entry['targetUid'] = $this->document->getPartof();
306
        }
307
308
        return $entry;
309
    }
310
311
    /**
312
     * This builds an array for one 3D menu entry
313
     *
314
     * @access protected
315
     *
316
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
317
     * @param bool $recursive : Whether to include the child entries
318
     *
319
     * @return array HMENU array for 3D menu entry
320
     */
321
    protected function getMenuEntryWithImage(array $entry, $recursive = false)
322
    {
323
        $entryArray = [];
324
325
        // don't filter if the entry type is collection
326
        if ($entry['type'] != 'collection') {
327
            if (!$this->isFound($entry)) {
328
                return $entryArray;
329
            }
330
        }
331
332
        // Set "title", "volume", "type" and "pagination" from $entry array.
333
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
334
        $entryArray['orderlabel'] = $entry['orderlabel'];
335
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['storagePid']);
336
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
337
        $entryArray['doNotLinkIt'] = 1;
338
        $entryArray['ITEM_STATE'] = 'HEADER';
339
340
        if ($entry['children'] == NULL) {
341
            $entryArray['description'] = $entry['description'];
342
            $entryArray['identifier'] = $entry['identifier'];
343
            $id = str_replace("LOG", "PHYS", $entry['id']);
344
            $entryArray['image'] = $this->document->getDoc()->getFileLocation($this->document->getDoc()->physicalStructureInfo[$id]['files']['THUMBS']);
345
            $entryArray['doNotLinkIt'] = 0;
346
            // index.php?tx_dlf%5Bid%5D=http%3A%2F%2Flink_to_METS_file.xml
347
            $entryArray['urlId'] = GeneralUtility::_GET('id');
348
            $entryArray['urlXml'] = $entry['points'];
349
            $entryArray['ITEM_STATE'] = 'ITEM';
350
351
            $this->addAuthorToAutocomplete($entryArray['author']);
352
            $this->addTitleToAutocomplete($entryArray['title']);
353
        }
354
355
        // Build sub-menu if available and called recursively.
356
        if (
357
            $recursive == true
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
358
            && !empty($entry['children'])
359
        ) {
360
            // Build sub-menu only if one of the following conditions apply:
361
            // 1. Current menu node points to another file
362
            // 2. Current menu node has no corresponding images
363
            if (
364
                is_string($entry['points'])
365
                || empty($this->document->getDoc()->smLinks['l2p'][$entry['id']])
366
            ) {
367
                $entryArray['_SUB_MENU'] = [];
368
                foreach ($entry['children'] as $child) {
369
                    $menuEntry = $this->getMenuEntryWithImage($child);
370
                    if (!empty($menuEntry)) {
371
                        $entryArray['_SUB_MENU'][] = $menuEntry;
372
                    }
373
                }
374
            }
375
        }
376
        return $entryArray;
377
    }
378
379
    /**
380
     * Check or possible combinations of requested params.
381
     *
382
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
383
     *
384
     * @return bool true if found, false otherwise
385
     */
386
    private function isFound($entry) {
387
        if (!empty($this->requestData['title'] && !empty($this->requestData['types']) && !empty($this->requestData['author']))) {
388
            return $this->isTitleFound($entry) && $this->isTypeFound($entry) && $this->isAuthorFound($entry);
389
        } else if (!empty($this->requestData['title']) && !empty($this->requestData['author'])) {
390
            return $this->isTitleFound($entry) && $this->isAuthorFound($entry);
391
        } else if (!empty($this->requestData['title']) && !empty($this->requestData['types'])) {
392
            return $this->isTitleFound($entry) && $this->isTypeFound($entry);
393
        } else if (!empty($this->requestData['author']) && !empty($this->requestData['types'])) {
394
            return $this->isAuthorFound($entry) && $this->isTypeFound($entry);
395
        } else if (!empty($this->requestData['title'])) {
396
            return $this->isTitleFound($entry);
397
        } else if (!empty($this->requestData['types'])) {
398
            return $this->isTypeFound($entry);
399
        } else if (!empty($this->requestData['author'])) {
400
            return $this->isAuthorFound($entry);
401
        } else {
402
            // no parameters so entry is matching
403
            return true;
404
        }
405
    }
406
407
    /**
408
     * Check if author is found.
409
     *
410
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
411
     *
412
     * @return bool true if found, false otherwise
413
     */
414
    private function isAuthorFound($entry) {
415
        $value = strtolower($entry['author']);
416
        $author = strtolower($this->requestData['author']);
417
        return str_contains($value, $author);
418
    }
419
420
    /**
421
     * Check if title is found.
422
     *
423
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
424
     *
425
     * @return bool true if found, false otherwise
426
     */
427
    private function isTitleFound($entry) {
428
        $value = strtolower($entry['label']);
429
        $title = strtolower($this->requestData['title']);
430
        return str_contains($value, $title);
431
    }
432
433
    /**
434
     * Check if type is found.
435
     *
436
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
437
     *
438
     * @return bool true if found, false otherwise
439
     */
440
    private function isTypeFound($entry) {
441
        return str_contains($entry['identifier'], $this->requestData['types']);
442
    }
443
444
    /**
445
     * Add author to the authors autocomplete array.
446
     *
447
     * @param string $author : author to be inserted to the authors autocomplete array
448
     *
449
     * @return void
450
     */
451
    private function addAuthorToAutocomplete($author) {
452
        if ($author != NULL && !(in_array($author, $this->authors))) {
453
            // additional check if actually not more than 1 author is included
454
            if (strpos($author, ',') !== false) {
455
                $authors = explode(",", $author);
456
                foreach ($authors as $value) {
457
                    if (!(in_array(trim($value), $this->authors))) {
458
                        $this->authors[] = trim($value);
459
                    }
460
                }
461
            } else {
462
                $this->authors[] = $author;
463
            }
464
        }
465
    }
466
467
    /**
468
     * Add title to the titles autocomplete array.
469
     *
470
     * @param string $title : title to be inserted to the titles autocomplete array
471
     *
472
     * @return void
473
     */
474
    private function addTitleToAutocomplete($title) {
475
        if (!(in_array($title, $this->titles)) && $title != NULL) {
476
            $this->titles[] = $title;
477
        }
478
    }
479
480
    /**
481
     * Get all types.
482
     *
483
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
484
     *
485
     * @return array of object types
486
     */
487
    private function getTypes($entry) {
488
        $types = [];
489
        $index = 0;
490
491
        if (!empty($entry[0]['children'])) {
492
            foreach ($entry[0]['children'] as $child) {
493
                $type = $this->getType($child);
494
                if (!(in_array($type, $types)) && $type != NULL) {
495
                    $types[$index] = $type;
496
                    $index++;
497
                }
498
            }
499
        }
500
501
        return $types;
502
    }
503
504
    /**
505
     * Get single type for given entry.
506
     *
507
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
508
     *
509
     * @return string type name without number
510
     */
511
    private function getType($entry) {
512
        $type = $entry['identifier'];
513
        if (!empty($type)) {
514
            return strtok($type, ',');
515
        }
516
        return $type;
517
    }
518
}
519