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 (#658)
by
unknown
04:01 queued 50s
created

TableOfContentsController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 1
nc 1
nop 0
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\Document;
15
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
16
use TYPO3\CMS\Core\Utility\MathUtility;
17
use \TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Extbase\Config...on\ConfigurationManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
use Kitodo\Dlf\Common\Helper;
20
use TYPO3\CMS\Core\Database\ConnectionPool;
21
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Extbase\Mvc\Controller\ActionController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
23
/**
24
 * Controller for plugin 'Table Of Contents' for the 'dlf' extension
25
 *
26
 * @author Sebastian Meyer <[email protected]>
27
 * @package TYPO3
28
 * @subpackage dlf
29
 * @access public
30
 */
31
class TableOfContentsController extends ActionController
32
{
33
    protected $prefixId = 'tx_dlf';
34
35
    /**
36
     * This holds the active entries according to the currently selected page
37
     *
38
     * @var array
39
     * @access protected
40
     */
41
    protected $activeEntries = [];
42
43
    /**
44
     * @var ExtensionConfiguration
45
     */
46
    protected $extensionConfiguration;
47
48
    /**
49
     * @var ConfigurationManager
50
     */
51
    protected $configurationManager;
52
53
    /**
54
     * @var \TYPO3\CMS\Core\Log\LogManager
55
     */
56
    protected $logger;
57
58
    /**
59
     * @var array
60
     */
61
    protected $pluginConf;
62
63
    /**
64
     * SearchController constructor.
65
     */
66
    public function __construct()
67
    {
68
        $this->configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
69
        $this->logger = GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager')->getLogger(__CLASS__);
70
        $this->extensionConfiguration = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('dlf');
71
72
        // Read plugin TS configuration.
73
        $this->pluginConf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_dlf_tableofcontents.'];
74
    }
75
76
    /**
77
     * This builds an array for one menu entry
78
     *
79
     * @access protected
80
     *
81
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Document->getLogicalStructure
82
     * @param bool $recursive : Whether to include the child entries
83
     *
84
     * @return array HMENU array for menu entry
85
     */
86
    protected function getMenuEntry(array $entry, $recursive = false)
87
    {
88
        $entryArray = [];
89
        // Set "title", "volume", "type" and "pagination" from $entry array.
90
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
91
        $entryArray['volume'] = $entry['volume'];
92
        $entryArray['orderlabel'] = $entry['orderlabel'];
93
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['pages']);
94
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
95
        $entryArray['_OVERRIDE_HREF'] = '';
96
        $entryArray['doNotLinkIt'] = 1;
97
        $entryArray['ITEM_STATE'] = 'NO';
98
        // Build menu links based on the $entry['points'] array.
99
        if (
100
            !empty($entry['points'])
101
            && MathUtility::canBeInterpretedAsInteger($entry['points'])
102
        ) {
103
            $entryArray['page'] = $entry['points'];
104
105
            $entryArray['doNotLinkIt'] = 0;
106
            if ($this->settings['basketButton']) {
107
                $entryArray['basketButton'] = [
108
                    'logId' => $entry['id'],
109
                    'startpage' => $entry['points']
110
                ];
111
            }
112
        } elseif (
113
            !empty($entry['points'])
114
            && is_string($entry['points'])
115
        ) {
116
            $entryArray['id'] = $entry['points'];
117
            $entryArray['page'] = 1;
118
            $entryArray['doNotLinkIt'] = 0;
119
            if ($this->settings['basketButton']) {
120
                $entryArray['basketButton'] = [
121
                    'logId' => $entry['id'],
122
                    'startpage' => $entry['points']
123
                ];
124
            }
125
        } elseif (!empty($entry['targetUid'])) {
126
            $entryArray['id'] = $entry['targetUid'];
127
            $entryArray['page'] = 1;
128
            $entryArray['doNotLinkIt'] = 0;
129
            if ($this->settings['basketButton']) {
130
                $entryArray['basketButton'] = [
131
                    'logId' => $entry['id'],
132
                    'startpage' => $entry['targetUid']
133
                ];
134
            }
135
        }
136
        // Set "ITEM_STATE" to "CUR" if this entry points to current page.
137
        if (in_array($entry['id'], $this->activeEntries)) {
138
            $entryArray['ITEM_STATE'] = 'CUR';
139
        }
140
        // Build sub-menu if available and called recursively.
141
        if (
142
            $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...
143
            && !empty($entry['children'])
144
        ) {
145
            // Build sub-menu only if one of the following conditions apply:
146
            // 1. "expAll" is set for menu
147
            // 2. Current menu node is in rootline
148
            // 3. Current menu node points to another file
149
            // 4. Current menu node has no corresponding images
150
            if (
151
                !empty($this->pluginConf['menuConf.']['expAll'])
152
                || $entryArray['ITEM_STATE'] == 'CUR'
153
                || is_string($entry['points'])
154
                || empty($this->doc->smLinks['l2p'][$entry['id']])
155
            ) {
156
                $entryArray['_SUB_MENU'] = [];
157
                foreach ($entry['children'] as $child) {
158
                    // Set "ITEM_STATE" to "ACT" if this entry points to current page and has sub-entries pointing to the same page.
159
                    if (in_array($child['id'], $this->activeEntries)) {
160
                        $entryArray['ITEM_STATE'] = 'ACT';
161
                    }
162
                    $entryArray['_SUB_MENU'][] = $this->getMenuEntry($child, true);
163
                }
164
            }
165
            // Append "IFSUB" to "ITEM_STATE" if this entry has sub-entries.
166
            $entryArray['ITEM_STATE'] = ($entryArray['ITEM_STATE'] == 'NO' ? 'IFSUB' : $entryArray['ITEM_STATE'] . 'IFSUB');
167
        }
168
        return $entryArray;
169
    }
170
171
    /**
172
     * The main method of the PlugIn
173
     *
174
     * @access public
175
     */
176
    public function mainAction()
177
    {
178
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
179
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
180
181
        // Check for typoscript configuration to prevent fatal error.
182
        if (empty($this->pluginConf['menuConf.'])) {
183
            $this->logger->warning('Incomplete plugin configuration');
1 ignored issue
show
Bug introduced by
The method warning() does not exist on TYPO3\CMS\Core\Log\LogManager. ( Ignorable by Annotation )

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

183
            $this->logger->/** @scrutinizer ignore-call */ 
184
                           warning('Incomplete plugin configuration');

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...
184
        }
185
186
        $this->view->assign('toc', $this->makeMenuArray($requestData));
187
    }
188
189
    /**
190
     * This builds a menu array for HMENU
191
     *
192
     * @access public
193
     * @param array $requestData
194
     * @return array HMENU array
195
     */
196
    public function makeMenuArray($requestData)
197
    {
198
        // Load current document.
199
        $this->loadDocument($requestData);
200
        if ($this->doc === null) {
201
            // Quit without doing anything if required variables are not set.
202
            return [];
203
        } else {
204
            if (!empty($requestData['logicalPage'])) {
205
                $requestData['page'] = $this->doc->getPhysicalPage($requestData['logicalPage']);
206
                // The logical page parameter should not appear again
207
                unset($requestData['logicalPage']);
208
            }
209
            // Set default values for page if not set.
210
            // $this->piVars['page'] may be integer or string (physical structure @ID)
211
            if (
212
                (int)$requestData['page'] > 0
213
                || empty($requestData['page'])
214
            ) {
215
                $requestData['page'] = MathUtility::forceIntegerInRange((int)$requestData['page'],
216
                    1, $this->doc->numPages, 1);
217
            } else {
218
                $requestData['page'] = array_search($requestData['page'], $this->doc->physicalStructure);
219
            }
220
            $requestData['double'] = MathUtility::forceIntegerInRange($requestData['double'],
221
                0, 1, 0);
222
        }
223
        $menuArray = [];
224
        // Does the document have physical elements or is it an external file?
225
        if (
226
            !empty($this->doc->physicalStructure)
227
            || !MathUtility::canBeInterpretedAsInteger($this->doc->uid)
228
        ) {
229
            // Get all logical units the current page or track is a part of.
230
            if (
231
                !empty($requestData['page'])
232
                && !empty($this->doc->physicalStructure)
233
            ) {
234
                $this->activeEntries = array_merge((array)$this->doc->smLinks['p2l'][$this->doc->physicalStructure[0]],
235
                    (array)$this->doc->smLinks['p2l'][$this->doc->physicalStructure[$requestData['page']]]);
236
                if (
237
                    !empty($requestData['double'])
238
                    && $requestData['page'] < $this->doc->numPages
239
                ) {
240
                    $this->activeEntries = array_merge($this->activeEntries,
241
                        (array)$this->doc->smLinks['p2l'][$this->doc->physicalStructure[$requestData['page'] + 1]]);
242
                }
243
            }
244
            // Go through table of contents and create all menu entries.
245
            foreach ($this->doc->tableOfContents as $entry) {
246
                $menuArray[] = $this->getMenuEntry($entry, true);
247
            }
248
        } else {
249
            // Go through table of contents and create top-level menu entries.
250
            foreach ($this->doc->tableOfContents as $entry) {
251
                $menuArray[] = $this->getMenuEntry($entry, false);
252
            }
253
            // Build table of contents from database.
254
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
255
                ->getQueryBuilderForTable('tx_dlf_documents');
256
257
            $excludeOtherWhere = '';
258
            if ($this->settings['excludeOther']) {
259
                $excludeOtherWhere = 'tx_dlf_documents.pid=' . intval($this->settings['pages']);
260
            }
261
            // Check if there are any metadata to suggest.
262
            $result = $queryBuilder
263
                ->select(
264
                    'tx_dlf_documents.uid AS uid',
265
                    'tx_dlf_documents.title AS title',
266
                    'tx_dlf_documents.volume AS volume',
267
                    'tx_dlf_documents.mets_label AS mets_label',
268
                    'tx_dlf_documents.mets_orderlabel AS mets_orderlabel',
269
                    'tx_dlf_structures_join.index_name AS type'
270
                )
271
                ->innerJoin(
272
                    'tx_dlf_documents',
273
                    'tx_dlf_structures',
274
                    'tx_dlf_structures_join',
275
                    $queryBuilder->expr()->eq(
276
                        'tx_dlf_structures_join.uid',
277
                        'tx_dlf_documents.structure'
278
                    )
279
                )
280
                ->from('tx_dlf_documents')
281
                ->where(
282
                    $queryBuilder->expr()->eq('tx_dlf_documents.partof', intval($this->doc->uid)),
283
                    $queryBuilder->expr()->eq('tx_dlf_structures_join.pid', intval($this->doc->pid)),
284
                    $excludeOtherWhere
285
                )
286
                ->addOrderBy('tx_dlf_documents.volume_sorting')
287
                ->addOrderBy('tx_dlf_documents.mets_orderlabel')
288
                ->execute();
289
290
            $allResults = $result->fetchAll();
291
292
            if (count($allResults) > 0) {
293
                $menuArray[0]['ITEM_STATE'] = 'CURIFSUB';
294
                $menuArray[0]['_SUB_MENU'] = [];
295
                foreach ($allResults as $resArray) {
296
                    $entry = [
297
                        'label' => !empty($resArray['mets_label']) ? $resArray['mets_label'] : $resArray['title'],
298
                        'type' => $resArray['type'],
299
                        'volume' => $resArray['volume'],
300
                        'orderlabel' => $resArray['mets_orderlabel'],
301
                        'pagination' => '',
302
                        'targetUid' => $resArray['uid']
303
                    ];
304
                    $menuArray[0]['_SUB_MENU'][] = $this->getMenuEntry($entry, false);
305
                }
306
            }
307
        }
308
        return $menuArray;
309
    }
310
311
    // TODO: Needs to be placed in an abstract class
312
    /**
313
     * Loads the current document into $this->doc
314
     *
315
     * @access protected
316
     *
317
     * @return void
318
     */
319
    protected function loadDocument($requestData)
320
    {
321
        // Check for required variable.
322
        if (
323
            !empty($requestData['id'])
324
            && !empty($this->settings['pages'])
325
        ) {
326
            // Should we exclude documents from other pages than $this->settings['pages']?
327
            $pid = (!empty($this->settings['excludeOther']) ? intval($this->settings['pages']) : 0);
328
            // Get instance of \Kitodo\Dlf\Common\Document.
329
            $this->doc = Document::getInstance($requestData['id'], $pid);
0 ignored issues
show
Bug Best Practice introduced by
The property doc does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
330
            if (!$this->doc->ready) {
331
                // Destroy the incomplete object.
332
                $this->doc = null;
333
                $this->logger->error('Failed to load document with UID ' . $requestData['id']);
1 ignored issue
show
Bug introduced by
The method error() does not exist on TYPO3\CMS\Core\Log\LogManager. ( Ignorable by Annotation )

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

333
                $this->logger->/** @scrutinizer ignore-call */ 
334
                               error('Failed to load document with UID ' . $requestData['id']);

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...
334
            } else {
335
                // Set configuration PID.
336
                $this->doc->cPid = $this->settings['pages'];
337
            }
338
        } elseif (!empty($requestData['recordId'])) {
339
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
340
                ->getQueryBuilderForTable('tx_dlf_documents');
341
342
            // Get UID of document with given record identifier.
343
            $result = $queryBuilder
344
                ->select('tx_dlf_documents.uid AS uid')
345
                ->from('tx_dlf_documents')
346
                ->where(
347
                    $queryBuilder->expr()->eq('tx_dlf_documents.record_id', $queryBuilder->expr()->literal($requestData['recordId'])),
348
                    Helper::whereExpression('tx_dlf_documents')
349
                )
350
                ->setMaxResults(1)
351
                ->execute();
352
353
            if ($resArray = $result->fetch()) {
354
                $requestData['id'] = $resArray['uid'];
355
                // Set superglobal $_GET array and unset variables to avoid infinite looping.
356
                $_GET[$this->prefixId]['id'] = $requestData['id'];
357
                unset($requestData['recordId'], $_GET[$this->prefixId]['recordId']);
358
                // Try to load document.
359
                $this->loadDocument();
0 ignored issues
show
Bug introduced by
The call to Kitodo\Dlf\Controller\Ta...troller::loadDocument() has too few arguments starting with requestData. ( Ignorable by Annotation )

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

359
                $this->/** @scrutinizer ignore-call */ 
360
                       loadDocument();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
360
            } else {
361
                $this->logger->error('Failed to load document with record ID "' . $requestData['recordId'] . '"');
362
            }
363
        } else {
364
            $this->logger->error('Invalid UID ' . $requestData['id'] . ' or PID ' . $this->settings['pages'] . ' for document loading');
365
        }
366
    }
367
}
368