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 (#661)
by
unknown
03:47 queued 43s
created

PageGridController::loadDocument()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 46
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 30
c 1
b 0
f 0
dl 0
loc 46
rs 8.5066
cc 7
nc 7
nop 1
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 TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
15
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...
16
use TYPO3\CMS\Core\Utility\GeneralUtility;
17
use TYPO3\CMS\Core\Utility\MathUtility;
18
use TYPO3\CMS\Core\Utility\PathUtility;
19
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
20
use Kitodo\Dlf\Common\Document;
21
use Kitodo\Dlf\Common\DocumentList;
22
use Kitodo\Dlf\Common\Helper;
23
use Kitodo\Dlf\Common\Indexer;
24
use Kitodo\Dlf\Common\Solr;
25
use TYPO3\CMS\Core\Database\Connection;
26
use TYPO3\CMS\Core\Database\ConnectionPool;
27
use \Kitodo\Dlf\Domain\Model\SearchForm;
0 ignored issues
show
Bug introduced by
The type Kitodo\Dlf\Domain\Model\SearchForm 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...
28
29
class PageGridController extends \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...
30
{
31
    public $prefixId = 'tx_dlf';
32
    public $extKey = 'dlf';
33
34
    /**
35
     * @var ConfigurationManager
36
     */
37
    protected $configurationManager;
38
39
    /**
40
     * @var \TYPO3\CMS\Core\Log\LogManager
41
     */
42
    protected $logger;
43
44
    /**
45
     * SearchController constructor.
46
     * @param $configurationManager
47
     */
48
    public function __construct(ConfigurationManager $configurationManager)
49
    {
50
        $this->configurationManager = $configurationManager;
51
        $this->logger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager')->getLogger(__CLASS__);
52
    }
53
54
    // TODO: Needs to be placed in an abstract class
55
    /**
56
     * Loads the current document into $this->doc
57
     *
58
     * @access protected
59
     *
60
     * @return void
61
     */
62
    protected function loadDocument($requestData)
63
    {
64
        // Check for required variable.
65
        if (
66
            !empty($requestData['id'])
67
            && !empty($this->settings['pages'])
68
        ) {
69
            // Should we exclude documents from other pages than $this->settings['pages']?
70
            $pid = (!empty($this->settings['excludeOther']) ? intval($this->settings['pages']) : 0);
71
            // Get instance of \Kitodo\Dlf\Common\Document.
72
            $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...
73
            if (!$this->doc->ready) {
74
                // Destroy the incomplete object.
75
                $this->doc = null;
76
                $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

76
                $this->logger->/** @scrutinizer ignore-call */ 
77
                               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...
77
            } else {
78
                // Set configuration PID.
79
                $this->doc->cPid = $this->settings['pages'];
80
            }
81
        } elseif (!empty($requestData['recordId'])) {
82
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
83
                ->getQueryBuilderForTable('tx_dlf_documents');
84
85
            // Get UID of document with given record identifier.
86
            $result = $queryBuilder
87
                ->select('tx_dlf_documents.uid AS uid')
88
                ->from('tx_dlf_documents')
89
                ->where(
90
                    $queryBuilder->expr()->eq('tx_dlf_documents.record_id', $queryBuilder->expr()->literal($requestData['recordId'])),
91
                    Helper::whereExpression('tx_dlf_documents')
92
                )
93
                ->setMaxResults(1)
94
                ->execute();
95
96
            if ($resArray = $result->fetch()) {
97
                $requestData['id'] = $resArray['uid'];
98
                // Set superglobal $_GET array and unset variables to avoid infinite looping.
99
                $_GET[$this->prefixId]['id'] = $requestData['id'];
100
                unset($requestData['recordId'], $_GET[$this->prefixId]['recordId']);
101
                // Try to load document.
102
                $this->loadDocument();
0 ignored issues
show
Bug introduced by
The call to Kitodo\Dlf\Controller\Pa...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

102
                $this->/** @scrutinizer ignore-call */ 
103
                       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...
103
            } else {
104
                $this->logger->error('Failed to load document with record ID "' . $requestData['recordId'] . '"');
105
            }
106
        } else {
107
            $this->logger->error('Invalid UID ' . $requestData['id'] . ' or PID ' . $this->settings['pages'] . ' for document loading');
108
        }
109
    }
110
111
    /**
112
     */
113
    public function mainAction()
114
    {
115
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
116
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
117
118
        $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get($this->extKey);
119
120
        $this->loadDocument($requestData);
121
        if (
122
            $this->doc === null
123
            || $this->doc->numPages < 1
124
            || empty($extConf['fileGrpThumbs'])
125
        ) {
126
            // Quit without doing anything if required variables are not set.
127
            return '';
128
        } else {
129
            // Set default values for page if not set.
130
            $requestData['pointer'] = MathUtility::forceIntegerInRange($requestData['pointer'], 0, $this->doc->numPages, 0);
131
        }
132
133
        if (!empty($requestData['logicalPage'])) {
134
            $requestData['page'] = $this->doc->getPhysicalPage($requestData['logicalPage']);
135
            // The logical page parameter should not appear
136
            unset($requestData['logicalPage']);
137
        }
138
        // Set some variable defaults.
139
        // $requestData['page'] may be integer or string (physical structure @ID)
140
        if (
141
            (int) $requestData['page'] > 0
142
            || empty($requestData['page'])
143
        ) {
144
            $requestData['page'] = MathUtility::forceIntegerInRange((int) $requestData['page'], 1, $this->doc->numPages, 1);
145
        } else {
146
            $requestData['page'] = array_search($requestData['page'], $this->doc->physicalStructure);
147
        }
148
        if (!empty($requestData['page'])) {
149
            $requestData['pointer'] = (int)(floor(($requestData['page'] - 1) / $this->settings['limit']));
150
        }
151
        if (
152
            !empty($requestData['pointer'])
153
            && (($requestData['pointer'] * $this->settings['limit']) + 1) <= $this->doc->numPages
154
        ) {
155
            $requestData['pointer'] = max($requestData['pointer'], 0);
156
        } else {
157
            $requestData['pointer'] = 0;
158
        }
159
        $entryArray = [];
160
161
        $additionalParams = [
162
            $this->prefixId . '[pointer]' => $requestData['pointer']
163
        ];
164
165
        // Iterate through visible page set and display thumbnails.
166
        for ($i = $requestData['pointer'] * $this->settings['limit'], $j = ($requestData['pointer'] + 1) * $this->settings['limit']; $i < $j; $i++) {
167
            // +1 because page counting starts at 1.
168
            $number = $i + 1;
169
            if ($number > $this->doc->numPages) {
170
                break;
171
            } else {
172
                $additionalParams[$this->prefixId . '[page]'] = $number;
173
                $entryArray[$number] = array_merge($this->getEntry($number, $requestData, $extConf), ['additionalParams' => $additionalParams]);
0 ignored issues
show
Bug introduced by
$this->getEntry($number, $requestData, $extConf) of type string is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

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

173
                $entryArray[$number] = array_merge(/** @scrutinizer ignore-type */ $this->getEntry($number, $requestData, $extConf), ['additionalParams' => $additionalParams]);
Loading history...
174
            }
175
        }
176
177
        $this->view->assign('requestData', $requestData);
178
        $this->view->assign('pageGridEntries', $entryArray);
179
        $this->view->assign('pageBrowser', $this->getPageBrowser($requestData));
180
    }
181
182
    protected function pi_getLL($label)
183
    {
184
        return $GLOBALS['TSFE']->sL('LLL:EXT:dlf/Resources/Private/Language/PageGrid.xml:' . $label);
185
    }
186
187
    /**
188
     * Renders entry for one page of the current document.
189
     *
190
     * @access protected
191
     *
192
     * @param int $number: The page to render
193
     * @param string $template: Parsed template subpart
194
     *
195
     * @return string The rendered entry ready for output
196
     */
197
    protected function getEntry($number, $requestData, $extConf)
198
    {
199
        // Set current page if applicable.
200
        if (!empty($requestData['page']) && $requestData['page'] == $number) {
201
            $markerArray['STATE'] = 'cur';
202
        } else {
203
            $markerArray['STATE'] = 'no';
204
        }
205
        // Set page number.
206
        $markerArray['NUMBER'] = $number;
207
        // Set pagination.
208
        $markerArray['PAGINATION'] = htmlspecialchars($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['orderlabel']);
209
        // Get thumbnail or placeholder.
210
        $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
211
        if (array_intersect($fileGrpsThumb, array_keys($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['files'])) !== []) {
212
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
213
                if (!empty($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['files'][$fileGrpThumb])) {
214
                    $thumbnailFile = $this->doc->getFileLocation($this->doc->physicalStructureInfo[$this->doc->physicalStructure[$number]]['files'][$fileGrpThumb]);
215
                    break;
216
                }
217
            }
218
        } elseif (!empty($this->settings['placeholder'])) {
219
            $thumbnailFile = $GLOBALS['TSFE']->tmpl->getFileName($this->settings['placeholder']);
220
        } else {
221
            $thumbnailFile = PathUtility::stripPathSitePrefix(ExtensionManagementUtility::extPath($this->extKey)) . 'Resources/Public/Images/PageGridPlaceholder.jpg';
222
        }
223
224
        $markerArray['THUMBNAIL'] = $thumbnailFile;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $thumbnailFile does not seem to be defined for all execution paths leading up to this point.
Loading history...
225
        // Get new plugin variables for typolink.
226
        $piVars = $requestData;
227
        // Unset no longer needed plugin variables.
228
        // unset($piVars['pagegrid']) is for DFG Viewer compatibility!
229
        unset($piVars['pointer'], $piVars['DATA'], $piVars['pagegrid']);
230
        $piVars['page'] = $number;
231
        return $markerArray;
232
    }
233
234
    /**
235
     * Renders the page browser
236
     *
237
     * @access protected
238
     *
239
     * @return string The rendered page browser ready for output
240
     */
241
    protected function getPageBrowser($requestData)
242
    {
243
        $outputArray = [];
244
        // Get overall number of pages.
245
        $maxPages = (int) ceil($this->doc->numPages / $this->settings['limit']);
246
        // Return empty pagebrowser if there is just one page.
247
        if ($maxPages < 2) {
248
            return '';
249
        }
250
        // Get separator.
251
        $separator = $this->pi_getLL('separator', ' - ');
0 ignored issues
show
Unused Code introduced by
The call to Kitodo\Dlf\Controller\Pa...dController::pi_getLL() has too many arguments starting with ' - '. ( Ignorable by Annotation )

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

251
        /** @scrutinizer ignore-call */ 
252
        $separator = $this->pi_getLL('separator', ' - ');

This check compares calls to functions or methods with their respective definitions. If the call has more 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...
252
        // Add link to previous page.
253
        if ($requestData['pointer'] > 0) {
254
            $outputArray[0] = [
255
                'text' => $this->pi_getLL('prevPage', '<') . $separator,
256
                'additionalParams' => [
257
                    $this->prefixId.'[pointer]' => $requestData['pointer'] - 1,
258
                    $this->prefixId.'[page]' => (($requestData['pointer'] - 1) * $this->settings['limit']) + 1
259
                ],
260
            ];
261
        } else {
262
            $outputArray[0] = [
263
                'text' => $this->pi_getLL('prevPage', '<'),
264
                'class' => 'prev-page not-active'
265
            ];
266
        }
267
        $i = 0;
268
        // Add links to pages.
269
        while ($i < $maxPages) {
270
            if ($i < 3 || ($i > $requestData['pointer'] - 3 && $i < $requestData['pointer'] + 3) || $i > $maxPages - 4) {
271
                if ($requestData['pointer'] != $i) {
272
                    $outputArray[$i+1] = [
273
                        'text' => sprintf($this->pi_getLL('page', '%d'), $i + 1) . $separator,
274
                        'additionalParams' => [
275
                            $this->prefixId.'[pointer]' => $i,
276
                            $this->prefixId.'[page]' => ($i * $this->settings['limit']) + 1
277
                        ],
278
                    ];
279
                } else {
280
                    $outputArray[$i+1] = [
281
                        'text' => sprintf($this->pi_getLL('page', '%d'), $i + 1) . $separator,
282
                        'class' => 'active'
283
                    ];
284
                }
285
                $skip = true;
286
            } elseif ($skip == true) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $skip does not seem to be defined for all execution paths leading up to this point.
Loading history...
287
                $outputArray[$i+1] = [
288
                    'text' => $this->pi_getLL('skip', '...') . $separator,
289
                    'class' => 'skipped'
290
                ];
291
                $skip = false;
292
            }
293
            $i++;
294
        }
295
        // Add link to next page.
296
        if ($requestData['pointer'] < $maxPages - 1) {
297
            $outputArray[$i+1] = [
298
                'text' => $this->pi_getLL('nextPage', '>'),
299
                'additionalParams' => [
300
                    $this->prefixId.'[pointer]' => $requestData['pointer'] + 1,
301
                    $this->prefixId.'[page]' => ($requestData['pointer'] + 1) * $this->settings['limit'] + 1
302
                ],
303
            ];
304
        } else {
305
            $outputArray[$i+1] = [
306
                'text' => $this->pi_getLL('nextPage', '>') . $separator,
307
                'class' => 'next-page not-active'
308
            ];
309
        }
310
        return $outputArray;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $outputArray returns the type array which is incompatible with the documented return type string.
Loading history...
311
    }
312
313
}