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 (#653)
by
unknown
03:22
created

ListViewController::mainAction()   D

Complexity

Conditions 22
Paths 88

Size

Total Lines 104
Code Lines 66

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 22
eloc 66
c 1
b 0
f 0
nc 88
nop 0
dl 0
loc 104
rs 4.1666

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 TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
15
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
16
use \TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
17
use Kitodo\Dlf\Common\Document;
18
use Kitodo\Dlf\Common\DocumentList;
19
use Kitodo\Dlf\Common\Helper;
20
use Kitodo\Dlf\Common\Solr;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
24
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
25
26
/**
27
 * Plugin 'List View' for the 'dlf' extension
28
 *
29
 * @author Sebastian Meyer <[email protected]>
30
 * @author Henrik Lochmann <[email protected]>
31
 * @author Frank Ulrich Weber <[email protected]>
32
 * @package TYPO3
33
 * @subpackage dlf
34
 * @access public
35
 */
36
class ListViewController extends ActionController
37
{
38
    const PARAMETER_PREFIX = 'tx_dlf';
39
40
    /**
41
     * This holds the field wrap of the metadata
42
     *
43
     * @var array
44
     * @access private
45
     */
46
    private $fieldwrap = [];
47
48
    /**
49
     * This holds the list
50
     *
51
     * @var \Kitodo\Dlf\Common\DocumentList
52
     * @access protected
53
     */
54
    protected $list;
55
56
    /**
57
     * Array of sorted metadata
58
     *
59
     * @var array
60
     * @access protected
61
     */
62
    protected $metadata = [];
63
64
    /**
65
     * Array of sortable metadata
66
     *
67
     * @var array
68
     * @access protected
69
     */
70
    protected $sortables = [];
71
72
    /**
73
     * @var \TYPO3\CMS\Core\Log\LogManager
74
     */
75
    protected $logger;
76
77
    /**
78
     * @var ConfigurationManager
79
     */
80
    protected $configurationManager;
81
82
    /**
83
     * Enriched documentList data for the view.
84
     *
85
     * @var array
86
     */
87
    protected $metadataList = [];
88
89
    /**
90
     * @var ExtensionConfiguration
91
     */
92
    protected $extensionConfiguration;
93
94
    /**
95
     * ListViewController constructor.
96
     * @param $configurationManager
97
     */
98
    public function __construct(ConfigurationManager $configurationManager)
99
    {
100
        $this->configurationManager = $configurationManager;
101
        $this->logger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\Log\LogManager')->getLogger(__CLASS__);
102
        $this->extensionConfiguration = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('dlf');
103
    }
104
105
    /**
106
     * Renders one entry of the list
107
     *
108
     * @access protected
109
     *
110
     * @param int $number: The number of the entry
111
     *
112
     * @return string The rendered entry ready for output
113
     */
114
    protected function getEntry($number)
115
    {
116
        $imgAlt = '';
117
        $metadata = $this->list[$number]['metadata'];
118
        foreach ($this->metadata as $index_name => $metaConf) {
119
            if (!empty($metadata[$index_name])) {
120
                $parsedValues = [];
121
                $fieldwrap = $this->getFieldWrap($index_name, $metaConf['wrap']);
122
123
                do {
124
                    $value = @array_shift($metadata[$index_name]);
125
                    // Link title to pageview.
126
                    if ($index_name == 'title') {
127
                        // Get title of parent document if needed.
128
                        if (empty($value) && $this->settings['getTitle']) {
129
                            $superiorTitle = Document::getTitle($this->list[$number]['uid'], true);
130
                            if (!empty($superiorTitle)) {
131
                                $value = '[' . $superiorTitle . ']';
132
                            }
133
                        }
134
                        // Set fake title if still not present.
135
                        if (empty($value)) {
136
                            $value = LocalizationUtility::translate(
137
                                'LLL:EXT:dlf/Resources/Private/Language/ListView.xml:noTitle',
138
                                'dlf'
139
                            );
140
                        }
141
                        $imgAlt = htmlspecialchars($value);
142
                        $value = htmlspecialchars($value);
143
144
                    } elseif ($index_name == 'owner' && !empty($value)) {
145
                        // Translate name of holding library.
146
                        $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['pages']));
147
                    } elseif ($index_name == 'type' && !empty($value)) {
148
                        // Translate document type.
149
                        $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['pages']));
150
                    } elseif ($index_name == 'language' && !empty($value)) {
151
                        // Translate ISO 639 language code.
152
                        $value = htmlspecialchars(Helper::getLanguageName($value));
153
                    } elseif (!empty($value)) {
154
                        $value = htmlspecialchars($value);
155
                    }
156
157
                    if (!empty($value)) {
158
                        $parsedValues[] = [
159
                            'value' => $value,
160
                            'wrap' => $fieldwrap['value.']
161
                        ];
162
                    }
163
                } while (count($metadata[$index_name]));
164
165
                if (!empty($parsedValues)) {
166
                    $field[$index_name] = [
167
                        'label' => [
168
                            'value' => htmlspecialchars($metaConf['label']),
169
                            'wrap' => $fieldwrap['key.'],
170
                        ],
171
                        'values' => $parsedValues,
172
                        'wrap' => $fieldwrap['all.']
173
                    ];
174
175
                    $this->metadataList[$number]['metadata'] = $field;
176
                }
177
            }
178
        }
179
180
        // Add thumbnail.
181
        if (!empty($this->list[$number]['thumbnail'])) {
182
            $this->metadataList[$number]['thumbnail'] = [
183
                'alt' => $imgAlt,
184
                'src' => $this->list[$number]['thumbnail']
185
            ];
186
        }
187
188
        if (!empty($this->list[$number]['subparts'])) {
189
            $this->getSubEntries($number);
190
        }
191
    }
192
193
    /**
194
     * Returns the parsed fieldwrap of a metadata
195
     *
196
     * @access private
197
     *
198
     * @param string $index_name: The index name of a metadata
199
     * @param string $wrap: The configured metadata wrap
200
     *
201
     * @return array The parsed fieldwrap
202
     */
203
    private function getFieldWrap($index_name, $wrap)
204
    {
205
        if (isset($this->fieldwrap[$index_name])) {
206
            return $this->fieldwrap[$index_name];
207
        } else {
208
            return $this->fieldwrap[$index_name] = $this->parseTS($wrap);
209
        }
210
    }
211
212
    /**
213
     * Parses a string into a Typoscript array
214
     *
215
     * @access protected
216
     *
217
     * @param string $string: The string to parse
218
     *
219
     * @return array The resulting typoscript array
220
     */
221
    protected function parseTS($string = '')
222
    {
223
        $parser = GeneralUtility::makeInstance(TypoScriptParser::class);
224
        $parser->parse($string);
225
        return $parser->setup;
226
    }
227
228
    /**
229
     * Renders all sub-entries of one entry
230
     *
231
     * @access protected
232
     *
233
     * @param int $number: The number of the entry
234
     *
235
     * @return string The rendered entries ready for output
236
     */
237
    protected function getSubEntries($number)
238
    {
239
        foreach ($this->list[$number]['subparts'] as $subpartKey => $subpart) {
240
            $imgAlt = '';
241
            foreach ($this->metadata as $index_name => $metaConf) {
242
                $parsedValues = [];
243
                $fieldwrap = $this->getFieldWrap($index_name, $metaConf['wrap']);
244
                do {
245
                    $value = @array_shift($subpart['metadata'][$index_name]);
246
                    // Link title to pageview.
247
                    if ($index_name == 'title') {
248
                        // Get title of parent document if needed.
249
                        if (empty($value) && $this->settings['getTitle']) {
250
                            $superiorTitle = Document::getTitle($subpart['uid'], true);
251
                            if (!empty($superiorTitle)) {
252
                                $value = '[' . $superiorTitle . ']';
253
                            }
254
                        }
255
                        // Set fake title if still not present.
256
                        if (empty($value)) {
257
                            $value = LocalizationUtility::translate(
258
                                'LLL:EXT:dlf/Resources/Private/Language/ListView.xml:noTitle',
259
                                'dlf'
260
                            );
261
                        }
262
                        $imgAlt = htmlspecialchars($value);
263
                        $value = htmlspecialchars($value);
264
                    } elseif ($index_name == 'owner' && !empty($value)) {
265
                        // Translate name of holding library.
266
                        $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['pages']));
267
                    } elseif ($index_name == 'type' && !empty($value)) {
268
                        // Translate document type.
269
                        $_value = $value;
270
                        $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['pages']));
271
                        // Add page number for single pages.
272
                        if ($_value == 'page') {
273
                            $value .= ' ' . intval($subpart['page']);
274
                        }
275
                    } elseif ($index_name == 'language' && !empty($value)) {
276
                        // Translate ISO 639 language code.
277
                        $value = htmlspecialchars(Helper::getLanguageName($value));
278
                    } elseif (!empty($value)) {
279
                        $value = htmlspecialchars($value);
280
                    }
281
282
                    if (!empty($value)) {
283
                        $parsedValues[] = [
284
                            'value' => $value,
285
                            'wrap' => $fieldwrap['value.']
286
                        ];
287
                    }
288
289
                } while (is_array($subpart['metadata'][$index_name]) && count($subpart['metadata'][$index_name]) > 0);
290
                if (!empty($parsedValues)) {
291
                    $field[$index_name] = [
292
                        'label' => [
293
                            'value' => htmlspecialchars($metaConf['label']),
294
                            'wrap' => $fieldwrap['key.'],
295
                        ],
296
                        'values' => $parsedValues,
297
                        'wrap' => $fieldwrap['all.']
298
                    ];
299
300
                    $this->metadataList[$number]['subparts'][$subpartKey]['metadata'] = $field;
301
                }
302
            }
303
304
            // Add thumbnail.
305
            if (!empty($subpart['thumbnail'])) {
306
                $this->metadataList[$number]['subparts'][$subpartKey]['thumbnail'] = [
307
                    'alt' => $imgAlt,
308
                    'src' => $subpart['thumbnail']
309
                ];
310
            }
311
        }
312
    }
313
314
    /**
315
     * Get metadata configuration from database
316
     *
317
     * @access protected
318
     *
319
     * @return void
320
     */
321
    protected function loadConfig()
322
    {
323
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
324
            ->getQueryBuilderForTable('tx_dlf_metadata');
325
326
        $result = $queryBuilder
327
            ->select(
328
                'tx_dlf_metadata.index_name AS index_name',
329
                'tx_dlf_metadata.wrap AS wrap',
330
                'tx_dlf_metadata.is_listed AS is_listed',
331
                'tx_dlf_metadata.is_sortable AS is_sortable'
332
            )
333
            ->from('tx_dlf_metadata')
334
            ->where(
335
                $queryBuilder->expr()->orX(
336
                    $queryBuilder->expr()->eq('tx_dlf_metadata.is_listed', 1),
337
                    $queryBuilder->expr()->eq('tx_dlf_metadata.is_sortable', 1)
338
                ),
339
                $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($this->settings['pages'])),
340
                Helper::whereExpression('tx_dlf_metadata')
341
            )
342
            ->orderBy('tx_dlf_metadata.sorting')
343
            ->execute();
344
345
        while ($resArray = $result->fetch()) {
346
            if ($resArray['is_listed']) {
347
                $this->metadata[$resArray['index_name']] = [
348
                    'wrap' => $resArray['wrap'],
349
                    'label' => Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->settings['pages'])
350
                ];
351
            }
352
            if ($resArray['is_sortable']) {
353
                $this->sortables[$resArray['index_name']] = Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->settings['pages']);
354
            }
355
        }
356
    }
357
358
    /**
359
     * The main method of the PlugIn
360
     */
361
    public function mainAction()
362
    {
363
        $sort = GeneralUtility::_GP(self::PARAMETER_PREFIX)['sort'];
364
        $pointer = GeneralUtility::_GP(self::PARAMETER_PREFIX)['pointer'];
365
        $logicalPage = GeneralUtility::_GP(self::PARAMETER_PREFIX)['logicalPage'];
366
367
        // Load the list.
368
        $this->list = GeneralUtility::makeInstance(DocumentList::class);
369
        $currentEntry = $pointer * $this->settings['limit'];
370
        $lastEntry = ($pointer + 1) * $this->settings['limit'];
371
372
        // Check if it's a list of database records or Solr documents.
373
        if (
374
            !empty($this->list->metadata['options']['source'])
375
            && $this->list->metadata['options']['source'] == 'collection'
376
            && ((!empty($sort['order']) && $sort['order'] != $this->list->metadata['options']['order'])
377
                || (isset($sort['asc']) && $sort['asc'] != $this->list->metadata['options']['order.asc']))
378
        ) {
379
            // Order list by given field.
380
            $this->list->sort($sort['order'], (bool) $sort['asc']);
381
            // Update list's metadata.
382
            $listMetadata = $this->list->metadata;
383
            $listMetadata['options']['order'] = $sort['order'];
384
            $listMetadata['options']['order.asc'] = (bool) $sort['asc'];
385
            $this->list->metadata = $listMetadata;
386
            // Save updated list.
387
            $this->list->save();
388
            // Reset pointer.
389
            $pointer = 0;
390
        } elseif (!empty($this->list->metadata['options']['source']) && $this->list->metadata['options']['source'] == 'search') {
391
            // Update list's metadata
392
            $listMetadata = $this->list->metadata;
393
            // Sort the list if applicable.
394
            if ((!empty($sort['order']) && $sort['order'] != $listMetadata['options']['order'])
395
                || (isset($sort['asc']) && $sort['asc'] != $listMetadata['options']['order.asc'])
396
            ) {
397
                // Update list's metadata.
398
                $listMetadata['options']['params']['sort'] = [$sort['order'] . "_sorting" => (bool) $sort['asc'] ? 'asc' : 'desc'];
399
                $listMetadata['options']['order'] = $sort['order'];
400
                $listMetadata['options']['order.asc'] = (bool) $sort['asc'];
401
                // Reset pointer.
402
                $pointer = 0;
403
            }
404
            // Set some query parameters
405
            $listMetadata['options']['params']['start'] = $currentEntry;
406
            $listMetadata['options']['params']['rows'] = $this->settings['limit'];
407
            // Search only if the query params have changed.
408
            if ($listMetadata['options']['params'] != $this->list->metadata['options']['params']) {
409
                // Instantiate search object.
410
                $solr = Solr::getInstance($this->list->metadata['options']['core']);
411
                if (!$solr->ready) {
412
                    $this->logger->error('Apache Solr not available');
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

412
                    $this->logger->/** @scrutinizer ignore-call */ 
413
                                   error('Apache Solr not available');

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...
413
                }
414
                // Set search parameters.
415
                $solr->cPid = $listMetadata['options']['pid'];
416
                $solr->params = $listMetadata['options']['params'];
417
                // Perform search.
418
                $this->list = $solr->search();
419
            }
420
            $this->list->metadata = $listMetadata;
421
            // Save updated list.
422
            $this->list->save();
423
            $currentEntry = 0;
424
            $lastEntry = $this->settings['limit'];
425
        }
426
427
        // Set some variable defaults.
428
        if (!empty($pointer) && (($pointer * $this->settings['limit']) + 1) <= $this->list->metadata['options']['numberOfToplevelHits']) {
429
            $pointer = max(intval($pointer), 0);
430
        } else {
431
            $pointer = 0;
432
        }
433
434
        // Load metadata configuration.
435
        $this->loadConfig();
436
        for ($currentEntry, $lastEntry; $currentEntry < $lastEntry; $currentEntry++) {
437
            if (empty($this->list[$currentEntry])) {
438
                break;
439
            } else {
440
                $this->getEntry($currentEntry);
441
            }
442
        }
443
444
        if ($currentEntry) {
445
            $currentEntry = ($pointer * $this->settings['limit']) + 1;
446
            $lastEntry = ($pointer * $this->settings['limit']) + $this->settings['limit'];
447
        }
448
449
        $this->view->assign('documentList', $this->list);
450
        $this->view->assign('metadataList', $this->metadataList);
451
        $this->view->assign('metadataConfig', $this->metadata);
452
        $this->view->assign('currentEntry', $currentEntry);
453
        $this->view->assign('lastEntry', $lastEntry);
454
        $this->view->assign('pointer', $pointer);
455
        $this->view->assign('sortables', $this->sortables);
456
        $this->view->assign('logicalPage', $logicalPage);
457
        $this->view->assign(
458
            'maxPages',
459
            intval(ceil($this->list->metadata['options']['numberOfToplevelHits'] / $this->settings['limit']))
460
        );
461
462
        $this->view->assign('pageToBasket', $this->settings['targetBasket']);
463
        $this->view->assign('forceAbsoluteUrl', !empty($this->extensionConfiguration['forceAbsoluteUrl']) ? 1 : 0);
464
        $this->view->assign('currentPageUid', $GLOBALS['TSFE']->id);
465
    }
466
}
467