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 — dev-extbase-fluid (#737)
by
unknown
02:53
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;
22
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
23
use Kitodo\Dlf\Domain\Repository\DocumentRepository;
24
25
class CollectionController extends AbstractController
26
{
27
    /**
28
     * This holds the hook objects
29
     *
30
     * @var array
31
     * @access protected
32
     */
33
    protected $hookObjects = [];
34
35
    /**
36
     * @var CollectionRepository
37
     */
38
    protected $collectionRepository;
39
40
    /**
41
     * @param CollectionRepository $collectionRepository
42
     */
43
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
44
    {
45
        $this->collectionRepository = $collectionRepository;
46
    }
47
48
    /**
49
     * @var DocumentRepository
50
     */
51
    protected $documentRepository;
52
53
    /**
54
     * @param DocumentRepository $documentRepository
55
     */
56
    public function injectDocumentRepository(DocumentRepository $documentRepository)
57
    {
58
        $this->documentRepository = $documentRepository;
59
    }
60
61
    /**
62
     * The main method of the plugin
63
     *
64
     * @return void
65
     */
66
    public function mainAction()
67
    {
68
        // access to GET parameter tx_dlf_collection['collection']
69
        $requestData = $this->request->getArguments();
70
71
        $collection = $requestData['collection'];
72
73
        // Quit without doing anything if required configuration variables are not set.
74
        if (empty($this->settings['pages'])) {
75
            $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

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