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.
Completed
Push — dev-extbase-fluid ( 10d1f1...3f6100 )
by Alexander
04:05 queued 04:02
created

ListViewController::getSubEntries()   D

Complexity

Conditions 21
Paths 99

Size

Total Lines 69
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

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

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

382
                    $this->logger->/** @scrutinizer ignore-call */ 
383
                                   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...
383
                }
384
                // Set search parameters.
385
                $solr->cPid = $listMetadata['options']['pid'];
386
                $solr->params = $listMetadata['options']['params'];
387
                // Perform search.
388
                $this->list = $solr->search();
389
            }
390
            $this->list->metadata = $listMetadata;
391
            // Save updated list.
392
            $this->list->save();
393
            $currentEntry = 0;
394
            $lastEntry = $this->settings['limit'];
395
        }
396
397
        // Set some variable defaults.
398
        if (!empty($pointer) && (($pointer * $this->settings['limit']) + 1) <= $this->list->metadata['options']['numberOfToplevelHits']) {
399
            $pointer = max(intval($pointer), 0);
400
        } else {
401
            $pointer = 0;
402
        }
403
404
        // Load metadata configuration.
405
        $this->loadConfig();
406
        for ($currentEntry, $lastEntry; $currentEntry < $lastEntry; $currentEntry++) {
407
            if (empty($this->list[$currentEntry])) {
408
                break;
409
            } else {
410
                $this->getEntry($currentEntry);
411
            }
412
        }
413
414
        if ($currentEntry) {
415
            $currentEntry = ($pointer * $this->settings['limit']) + 1;
416
            $lastEntry = ($pointer * $this->settings['limit']) + $this->settings['limit'];
417
        }
418
419
        // Pagination of Results
420
        // pass the currentPage to the fluid template to calculate current index of search result
421
        if (empty($requestData['@widget_0'])) {
422
            $widgetPage = ['currentPage' => 1];
423
        } else {
424
            $widgetPage = $requestData['@widget_0'];
425
        }
426
427
        // convert documentList to array --> use widget.pagination viewhelper
428
        $documentList = [];
429
        foreach ($this->list as $listElement) {
430
            $documentList[] = $listElement;
431
        }
432
        $this->view->assign('widgetPage', $widgetPage);
433
        $this->view->assign('documentList', $this->list);
434
        $this->view->assign('documentListArray', $documentList);
435
        $this->view->assign('metadataList', $this->metadataList);
436
        $this->view->assign('metadataConfig', $this->metadata);
437
        $this->view->assign('currentEntry', $currentEntry);
438
        $this->view->assign('lastEntry', $lastEntry);
439
        $this->view->assign('sortables', $this->sortables);
440
        $this->view->assign('logicalPage', $logicalPage);
441
        $this->view->assign(
442
            'maxPages',
443
            intval(ceil($this->list->metadata['options']['numberOfToplevelHits'] / $this->settings['limit']))
444
        );
445
        $this->view->assign('forceAbsoluteUrl', !empty($this->extConf['forceAbsoluteUrl']) ? 1 : 0);
446
    }
447
}
448