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 (#821)
by
unknown
08:50
created

TableOfContentsController   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 227
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 114
c 3
b 0
f 0
dl 0
loc 227
rs 8.96
wmc 43

4 Methods

Rating   Name   Duplication   Size   Complexity  
C makeMenuArray() 0 82 17
A mainAction() 0 3 1
A resolveMenuEntry() 0 14 6
D getMenuEntry() 0 81 19

How to fix   Complexity   

Complex Class

Complex classes like TableOfContentsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TableOfContentsController, and based on these observations, apply Extract Interface, too.

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 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 builds an array for one menu entry
39
     *
40
     * @access protected
41
     *
42
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
43
     * @param bool $recursive : Whether to include the child entries
44
     *
45
     * @return array HMENU array for menu entry
46
     */
47
    protected function getMenuEntry(array $entry, $recursive = false)
48
    {
49
        $entryArray = [];
50
        // Set "title", "volume", "type" and "pagination" from $entry array.
51
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
52
        $entryArray['volume'] = $entry['volume'];
53
        $entryArray['orderlabel'] = $entry['orderlabel'];
54
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['storagePid']);
55
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
56
        $entryArray['_OVERRIDE_HREF'] = '';
57
        $entryArray['doNotLinkIt'] = 1;
58
        $entryArray['ITEM_STATE'] = 'NO';
59
        // Build menu links based on the $entry['points'] array.
60
        if (
61
            !empty($entry['points'])
62
            && MathUtility::canBeInterpretedAsInteger($entry['points'])
63
        ) {
64
            $entryArray['page'] = $entry['points'];
65
66
            $entryArray['doNotLinkIt'] = 0;
67
            if ($this->settings['basketButton']) {
68
                $entryArray['basketButton'] = [
69
                    'logId' => $entry['id'],
70
                    'startpage' => $entry['points']
71
                ];
72
            }
73
        } elseif (
74
            !empty($entry['points'])
75
            && is_string($entry['points'])
76
        ) {
77
            $entryArray['id'] = $entry['points'];
78
            $entryArray['page'] = 1;
79
            $entryArray['doNotLinkIt'] = 0;
80
            if ($this->settings['basketButton']) {
81
                $entryArray['basketButton'] = [
82
                    'logId' => $entry['id'],
83
                    'startpage' => $entry['points']
84
                ];
85
            }
86
        } elseif (!empty($entry['targetUid'])) {
87
            $entryArray['id'] = $entry['targetUid'];
88
            $entryArray['page'] = 1;
89
            $entryArray['doNotLinkIt'] = 0;
90
            if ($this->settings['basketButton']) {
91
                $entryArray['basketButton'] = [
92
                    'logId' => $entry['id'],
93
                    'startpage' => $entry['targetUid']
94
                ];
95
            }
96
        }
97
        // Set "ITEM_STATE" to "CUR" if this entry points to current page.
98
        if (in_array($entry['id'], $this->activeEntries)) {
99
            $entryArray['ITEM_STATE'] = 'CUR';
100
        }
101
        // Build sub-menu if available and called recursively.
102
        if (
103
            $recursive === true
104
            && !empty($entry['children'])
105
        ) {
106
            // Build sub-menu only if one of the following conditions apply:
107
            // 1. Current menu node is in rootline
108
            // 2. Current menu node points to another file
109
            // 3. Current menu node has no corresponding images
110
            if (
111
                $entryArray['ITEM_STATE'] == 'CUR'
112
                || is_string($entry['points'])
113
                || empty($this->document->getDoc()->smLinks['l2p'][$entry['id']])
114
            ) {
115
                $entryArray['_SUB_MENU'] = [];
116
                foreach ($entry['children'] as $child) {
117
                    // Set "ITEM_STATE" to "ACT" if this entry points to current page and has sub-entries pointing to the same page.
118
                    if (in_array($child['id'], $this->activeEntries)) {
119
                        $entryArray['ITEM_STATE'] = 'ACT';
120
                    }
121
                    $entryArray['_SUB_MENU'][] = $this->getMenuEntry($child, true);
122
                }
123
            }
124
            // Append "IFSUB" to "ITEM_STATE" if this entry has sub-entries.
125
            $entryArray['ITEM_STATE'] = ($entryArray['ITEM_STATE'] == 'NO' ? 'IFSUB' : $entryArray['ITEM_STATE'] . 'IFSUB');
126
        }
127
        return $entryArray;
128
    }
129
130
    /**
131
     * If $entry references an external METS file (as mptr), try to resolve its database UID
132
     * and return an updated $entry.
133
     *
134
     * This is so that when linking from a child document back to its parent,
135
     * that link is via UID, so that subsequently the parent's TOC is built from database.
136
     *
137
     * @param array $entry
138
     * @return string|int
139
     */
140
    protected function resolveMenuEntry($entry)
141
    {
142
        if (!empty($entry['points']) && is_string($entry['points'])) {
143
            $doc = Doc::getInstance($entry['points'], ['storagePid' => $this->settings['storagePid']]);
144
            if ($doc !== null && !empty($doc->recordId)) {
145
                $model = $this->documentRepository->findOneByRecordId($doc->recordId);
0 ignored issues
show
Bug introduced by
The method findOneByRecordId() does not exist on Kitodo\Dlf\Domain\Repository\DocumentRepository. 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

145
                /** @scrutinizer ignore-call */ 
146
                $model = $this->documentRepository->findOneByRecordId($doc->recordId);
Loading history...
146
                if ($model !== null) {
147
                    unset($entry['points']);
148
                    $entry['targetUid'] = $model->getUid();
0 ignored issues
show
Bug introduced by
The method getUid() 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

148
                    /** @scrutinizer ignore-call */ 
149
                    $entry['targetUid'] = $model->getUid();

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...
149
                }
150
            }
151
        }
152
153
        return $entry;
154
    }
155
156
    /**
157
     * The main method of the plugin
158
     *
159
     * @return void
160
     */
161
    public function mainAction()
162
    {
163
        $this->view->assign('toc', $this->makeMenuArray());
164
    }
165
166
    /**
167
     * This builds a menu array for HMENU
168
     *
169
     * @access public
170
     * @return array HMENU array
171
     */
172
    public function makeMenuArray()
173
    {
174
        // Load current document.
175
        $this->loadDocument($this->requestData);
176
        if (
177
            $this->document === null
178
            || $this->document->getDoc() === null
179
        ) {
180
            // Quit without doing anything if required variables are not set.
181
            return [];
182
        } else {
183
            if (!empty($this->requestData['logicalPage'])) {
184
                $this->requestData['page'] = $this->document->getDoc()->getPhysicalPage($this->requestData['logicalPage']);
185
                // The logical page parameter should not appear again
186
                unset($this->requestData['logicalPage']);
187
            }
188
            // Set default values for page if not set.
189
            // $this->piVars['page'] may be integer or string (physical structure @ID)
190
            if (
191
                (int) $this->requestData['page'] > 0
192
                || empty($this->requestData['page'])
193
            ) {
194
                $this->requestData['page'] = MathUtility::forceIntegerInRange((int) $this->requestData['page'],
195
                    1, $this->document->getDoc()->numPages, 1);
196
            } else {
197
                $this->requestData['page'] = array_search($this->requestData['page'], $this->document->getDoc()->physicalStructure);
198
            }
199
            $this->requestData['double'] = MathUtility::forceIntegerInRange($this->requestData['double'],
200
                0, 1, 0);
201
        }
202
        $menuArray = [];
203
        // Does the document have physical elements or is it an external file?
204
        if (
205
            !empty($this->document->getDoc()->physicalStructure)
206
            || !MathUtility::canBeInterpretedAsInteger($this->requestData['id'])
207
        ) {
208
            // Get all logical units the current page or track is a part of.
209
            if (
210
                !empty($this->requestData['page'])
211
                && !empty($this->document->getDoc()->physicalStructure)
212
            ) {
213
                $this->activeEntries = array_merge((array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[0]],
214
                    (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page']]]);
215
                if (
216
                    !empty($this->requestData['double'])
217
                    && $this->requestData['page'] < $this->document->getDoc()->numPages
218
                ) {
219
                    $this->activeEntries = array_merge($this->activeEntries,
220
                        (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page'] + 1]]);
221
                }
222
            }
223
            // Go through table of contents and create all menu entries.
224
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
225
                $menuArray[] = $this->getMenuEntry($this->resolveMenuEntry($entry), true);
0 ignored issues
show
Bug introduced by
$this->resolveMenuEntry($entry) of type integer|string is incompatible with the type array expected by parameter $entry of Kitodo\Dlf\Controller\Ta...troller::getMenuEntry(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

225
                $menuArray[] = $this->getMenuEntry(/** @scrutinizer ignore-type */ $this->resolveMenuEntry($entry), true);
Loading history...
226
            }
227
        } else {
228
            // Go through table of contents and create top-level menu entries.
229
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
230
                $menuArray[] = $this->getMenuEntry($this->resolveMenuEntry($entry), false);
231
            }
232
            // Build table of contents from database.
233
            $result = $this->documentRepository->getTableOfContentsFromDb($this->document->getUid(), $this->document->getPid(), $this->settings);
234
235
            $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

235
            /** @scrutinizer ignore-call */ 
236
            $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...
236
237
            if (count($allResults) > 0) {
238
                $menuArray[0]['ITEM_STATE'] = 'CURIFSUB';
239
                $menuArray[0]['_SUB_MENU'] = [];
240
                foreach ($allResults as $resArray) {
241
                    $entry = [
242
                        'label' => !empty($resArray['mets_label']) ? $resArray['mets_label'] : $resArray['title'],
243
                        'type' => $resArray['type'],
244
                        'volume' => $resArray['volume'],
245
                        'orderlabel' => $resArray['mets_orderlabel'],
246
                        'pagination' => '',
247
                        'targetUid' => $resArray['uid']
248
                    ];
249
                    $menuArray[0]['_SUB_MENU'][] = $this->getMenuEntry($entry, false);
250
                }
251
            }
252
        }
253
        return $menuArray;
254
    }
255
}
256