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 (#715)
by Alexander
05:05 queued 02:34
created

CollectionController::showSingleCollection()   F

Complexity

Conditions 17
Paths 794

Size

Total Lines 112
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 76
c 1
b 0
f 0
nc 794
nop 1
dl 0
loc 112
rs 1.3361

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 Kitodo\Dlf\Common\DocumentList;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Solr;
17
use Kitodo\Dlf\Domain\Model\Document;
18
use Kitodo\Dlf\Domain\Model\Collection;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Core\Utility\MathUtility;
21
use TYPO3\CMS\Frontend\Page\PageRepository;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Frontend\Page\PageRepository 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
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
23
24
class CollectionController extends AbstractController
25
{
26
    /**
27
     * This holds the hook objects
28
     *
29
     * @var array
30
     * @access protected
31
     */
32
    protected $hookObjects = [];
33
34
    /**
35
     * @var CollectionRepository
36
     */
37
    protected $collectionRepository;
38
39
    /**
40
     * @param CollectionRepository $collectionRepository
41
     */
42
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
43
    {
44
        $this->collectionRepository = $collectionRepository;
45
    }
46
47
    /**
48
     * The main method of the plugin
49
     *
50
     * @return void
51
     */
52
    public function mainAction()
53
    {
54
        // access to GET parameter tx_dlf_collection['collection']
55
        $requestData = $this->request->getArguments();
56
57
        $collection = $requestData['collection'];
58
59
        // Quit without doing anything if required configuration variables are not set.
60
        if (empty($this->settings['pages'])) {
61
            $this->logger->warning('Incomplete plugin configuration');
1 ignored issue
show
Bug introduced by
The method warning() 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

61
            $this->logger->/** @scrutinizer ignore-call */ 
62
                           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...
62
        }
63
64
        // Get hook objects.
65
        // TODO: $this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
66
67
        if ($collection) {
68
            $this->showSingleCollection($this->collectionRepository->findByUid($collection[0]));
69
        } else {
70
            $this->showCollectionList();
71
        }
72
73
        $this->view->assign('currentPageUid', $GLOBALS['TSFE']->id);
74
    }
75
76
    /**
77
     * Builds a collection list
78
     * @return void
79
     */
80
    protected function showCollectionList()
81
    {
82
        $solr = Solr::getInstance($this->settings['solrcore']);
83
84
        if (!$solr->ready) {
85
            $this->logger->error('Apache Solr not available');
86
            return;
87
        }
88
        // We only care about the UID and partOf in the results and want them sorted
89
        $params['fields'] = 'uid,partof';
90
        $params['sort'] = ['uid' => 'asc'];
91
        $collections = [];
92
93
        // Sort collections according to flexform configuration
94
        if ($this->settings['collections']) {
95
            $sortedCollections = [];
96
            foreach (GeneralUtility::intExplode(',', $this->settings['collections']) as $uid) {
97
                $sortedCollections[$uid] = $this->collectionRepository->findByUid($uid);
98
            }
99
            $collections = $sortedCollections;
100
        }
101
102
        if (count($collections) == 1 && empty($this->settings['dont_show_single'])) {
103
            $this->showSingleCollection(array_pop($collections));
104
        }
105
106
        $processedCollections = [];
107
108
        // Process results.
109
        foreach ($collections as $collection) {
110
            $solr_query = '';
111
            if ($collection->getIndexSearch() != '') {
112
                $solr_query .= '(' . $collection->getIndexSearch() . ')';
113
            } else {
114
                $solr_query .= 'collection:("' . Solr::escapeQuery($collection->getIndexName()) . '")';
115
            }
116
            $partOfNothing = $solr->search_raw($solr_query . ' AND partof:0 AND toplevel:true', $params);
117
            $partOfSomething = $solr->search_raw($solr_query . ' AND NOT partof:0 AND toplevel:true', $params);
118
            // Titles are all documents that are "root" elements i.e. partof == 0
119
            $collectionInfo['titles'] = [];
120
            foreach ($partOfNothing as $doc) {
121
                $collectionInfo['titles'][$doc->uid] = $doc->uid;
122
            }
123
            // Volumes are documents that are both
124
            // a) "leaf" elements i.e. partof != 0
125
            // b) "root" elements that are not referenced by other documents ("root" elements that have no descendants)
126
            $collectionInfo['volumes'] = $collectionInfo['titles'];
127
            foreach ($partOfSomething as $doc) {
128
                $collectionInfo['volumes'][$doc->uid] = $doc->uid;
129
                // If a document is referenced via partof, it’s not a volume anymore.
130
                unset($collectionInfo['volumes'][$doc->partof]);
131
            }
132
133
            // Generate random but unique array key taking priority into account.
134
            do {
135
                $_key = ($collectionInfo['priority'] * 1000) + mt_rand(0, 1000);
136
            } while (!empty($processedCollections[$_key]));
137
138
            $processedCollections[$_key]['collection'] = $collection;
139
            $processedCollections[$_key]['info'] = $collectionInfo;
140
        }
141
142
        // Randomize sorting?
143
        if (!empty($this->settings['randomize'])) {
144
            ksort($processedCollections, SORT_NUMERIC);
145
        }
146
147
        // TODO: Hook for getting custom collection hierarchies/subentries (requested by SBB).
148
        /*    foreach ($this->hookObjects as $hookObj) {
149
                if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
150
                    $hookObj->showCollectionList_getCustomCollectionList($this, $this->settings['templateFile'], $content, $markerArray);
151
                }
152
            }
153
        */
154
155
        $this->view->assign('collections', $processedCollections);
156
    }
157
158
    /**
159
     * Builds a collection's list
160
     *
161
     * @access protected
162
     *
163
     * @param \Kitodo\Dlf\Domain\Model\Collection The collection object
0 ignored issues
show
Bug introduced by
The type Kitodo\Dlf\Controller\The 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...
164
     *
165
     * @return void
166
     */
167
    protected function showSingleCollection(\Kitodo\Dlf\Domain\Model\Collection $collection)
168
    {
169
        // access storagePid from TypoScript
170
        $pageSettings = $this->configurationManager->getConfiguration($this->configurationManager::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
171
        $this->settings['pages'] = $pageSettings["plugin."]["tx_dlf."]["persistence."]["storagePid"];
172
173
        // Fetch corresponding document UIDs from Solr.
174
        if ($collection->getIndexSearch() != '') {
175
            $solr_query = '(' . $collection->getIndexSearch() . ')';
176
        } else {
177
            $solr_query = 'collection:("' . Solr::escapeQuery($collection->getIndexName()) . '") AND toplevel:true';
178
        }
179
        $solr = Solr::getInstance($this->settings['solrcore']);
180
        if (!$solr->ready) {
181
            $this->logger->error('Apache Solr not available');
182
            return;
183
        }
184
        $params['fields'] = 'uid';
185
        $params['sort'] = ['uid' => 'asc'];
186
        $solrResult = $solr->search_raw($solr_query, $params);
187
        // Initialize array
188
        $documentSet = [];
189
        foreach ($solrResult as $doc) {
190
            if ($doc->uid) {
191
                $documentSet[] = $doc->uid;
192
            }
193
        }
194
        $documentSet = array_unique($documentSet);
195
196
        $this->settings['documentSets'] = implode(',', $documentSet);
197
198
        $documents = $this->documentRepository->findDocumentsBySettings($this->settings);
199
200
        $toplevel = [];
201
        $subparts = [];
202
        $listMetadata = [];
203
        // Process results.
204
        /** @var Document $document */
205
        foreach ($documents as $document) {
206
            if (empty($listMetadata)) {
207
                $listMetadata = [
208
                    'label' => htmlspecialchars($collection->getLabel()),
209
                    'description' => $collection->getDescription(),
210
                    'thumbnail' => htmlspecialchars($collection->getThumbnail()),
211
                    'options' => [
212
                        'source' => 'collection',
213
                        'select' => $id,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id seems to be never defined.
Loading history...
214
                        'userid' => $collection->getFeCruserId(),
215
                        'params' => ['filterquery' => [['query' => 'collection_faceting:("' . $collection->getIndexName() . '")']]],
216
                        'core' => '',
217
                        'order' => 'title',
218
                        'order.asc' => true
219
                    ]
220
                ];
221
            }
222
            // Prepare document's metadata for sorting.
223
            $sorting = unserialize($document->getMetadataSorting());
224
            if (!empty($sorting['type']) && MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
225
                $sorting['type'] = Helper::getIndexNameFromUid($sorting['type'], 'tx_dlf_structures', $this->settings['pages']);
226
            }
227
            if (!empty($sorting['owner']) && MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
228
                $sorting['owner'] = Helper::getIndexNameFromUid($sorting['owner'], 'tx_dlf_libraries', $this->settings['pages']);
229
            }
230
            if (!empty($sorting['collection']) && MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
231
                $sorting['collection'] = Helper::getIndexNameFromUid($sorting['collection'], 'tx_dlf_collections', $this->settings['pages']);
232
            }
233
            // Split toplevel documents from volumes.
234
            if ($document->getPartof() == 0) {
235
                $toplevel[$document->getUid()] = [
236
                    'u' => $document->getUid(),
237
                    'h' => '',
238
                    's' => $sorting,
239
                    'p' => []
240
                ];
241
            } else {
242
                // volume_sorting should be always set - but it's not a required field. We append the uid to the array key to make it always unique.
243
                $subparts[$document->getPartof()][$document->getVolumeSorting() . str_pad($document->getUid(), 9, '0', STR_PAD_LEFT)] = [
244
                    'u' => $document->getUid(),
245
                    'h' => '',
246
                    's' => $sorting,
247
                    'p' => []
248
                ];
249
            }
250
        }
251
252
        // Add volumes to the corresponding toplevel documents.
253
        foreach ($subparts as $partof => $parts) {
254
            ksort($parts);
255
            foreach ($parts as $part) {
256
                if (!empty($toplevel[$partof])) {
257
                    $toplevel[$partof]['p'][] = ['u' => $part['u']];
258
                } else {
259
                    $toplevel[$part['u']] = $part;
260
                }
261
            }
262
        }
263
        // Save list of documents.
264
        $list = GeneralUtility::makeInstance(DocumentList::class);
265
        $list->reset();
266
        $list->add(array_values($toplevel));
267
        $listMetadata['options']['numberOfToplevelHits'] = count($list);
268
        $list->metadata = $listMetadata;
269
        $list->sort('title');
270
        $list->save();
271
        // Clean output buffer.
272
        ob_end_clean();
273
274
        $uri = $this->uriBuilder
275
            ->reset()
276
            ->setTargetPageUid($this->settings['targetPid'])
277
            ->uriFor('main', [], 'ListView', 'dlf', 'ListView');
278
        $this->redirectToURI($uri);
279
    }
280
}
281