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 (#754)
by Alexander
02:39
created

SearchController   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 414
Duplicated Lines 0 %

Importance

Changes 23
Bugs 0 Features 0
Metric Value
eloc 181
c 23
b 0
f 0
dl 0
loc 414
rs 3.6
wmc 60

10 Methods

Rating   Name   Duplication   Size   Complexity  
A injectMetadataRepository() 0 3 1
A injectCollectionRepository() 0 3 1
A searchAction() 0 7 1
A mainAction() 0 44 5
B getFacetsMenuEntry() 0 56 7
B addCurrentCollection() 0 22 7
D makeFacetsMenuArray() 0 102 18
A addExtendedSearch() 0 29 6
B addCurrentDocument() 0 28 9
A addFacetsMenu() 0 19 5

How to fix   Complexity   

Complex Class

Complex classes like SearchController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SearchController, and based on these observations, apply Extract Interface, too.

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\Doc;
15
use Kitodo\Dlf\Common\DocumentList;
16
use Kitodo\Dlf\Common\Helper;
17
use Kitodo\Dlf\Common\Indexer;
18
use Kitodo\Dlf\Common\Solr;
19
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
22
use Kitodo\Dlf\Domain\Repository\MetadataRepository;
23
24
class SearchController extends AbstractController
25
{
26
    /**
27
     * @var CollectionRepository
28
     */
29
    protected $collectionRepository;
30
31
    /**
32
     * @param CollectionRepository $collectionRepository
33
     */
34
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
35
    {
36
        $this->collectionRepository = $collectionRepository;
37
    }
38
39
    /**
40
     * @var MetadataRepository
41
     */
42
    protected $metadataRepository;
43
44
    /**
45
     * @param MetadataRepository $metadataRepository
46
     */
47
    public function injectMetadataRepository(MetadataRepository $metadataRepository)
48
    {
49
        $this->metadataRepository = $metadataRepository;
50
    }
51
52
    /**
53
     * Search Action
54
     *
55
     * @return void
56
     */
57
    public function searchAction()
58
    {
59
        // if search was triggered, get search parameters from POST variables
60
        $searchParams = $this->getParametersSafely('searchParameter');
61
62
        // output is done by main action
63
        $this->forward('main', null, null, ['searchParameter' => $searchParams]);
64
    }
65
66
    /**
67
     * Main action
68
     *
69
     * @return void
70
     */
71
    public function mainAction()
72
    {
73
        // Quit without doing anything if required variables are not set.
74
        if (empty($this->settings['solrcore'])) {
75
            $this->logger->warning('Incomplete plugin configuration');
76
            return;
77
        }
78
79
        // if search was triggered, get search parameters from POST variables
80
        $searchParams = $this->getParametersSafely('searchParameter');
81
82
        // get all sortable metadata records
83
        $sortableMetadata = $this->metadataRepository->findByIsSortable(true);
0 ignored issues
show
Bug introduced by
The method findByIsSortable() does not exist on Kitodo\Dlf\Domain\Repository\MetadataRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

83
        /** @scrutinizer ignore-call */ 
84
        $sortableMetadata = $this->metadataRepository->findByIsSortable(true);
Loading history...
84
85
        // get all metadata records to be shown in results
86
        $listedMetadata = $this->metadataRepository->findByIsListed(true);
0 ignored issues
show
Bug introduced by
The method findByIsListed() does not exist on Kitodo\Dlf\Domain\Repository\MetadataRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

86
        /** @scrutinizer ignore-call */ 
87
        $listedMetadata = $this->metadataRepository->findByIsListed(true);
Loading history...
87
88
        // get results from search
89
        // find all documents from Solr
90
        if (!empty($searchParams)) {
91
            $solrResults = $this->documentRepository->findSolrByCollection('', $this->settings, $searchParams, $listedMetadata);
0 ignored issues
show
Bug introduced by
It seems like $searchParams can also be of type string; however, parameter $searchParams of Kitodo\Dlf\Domain\Reposi...:findSolrByCollection() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

91
            $solrResults = $this->documentRepository->findSolrByCollection('', $this->settings, /** @scrutinizer ignore-type */ $searchParams, $listedMetadata);
Loading history...
Bug introduced by
'' of type string is incompatible with the type TYPO3\CMS\Extbase\Persistence\Generic\QueryResult expected by parameter $collections of Kitodo\Dlf\Domain\Reposi...:findSolrByCollection(). ( Ignorable by Annotation )

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

91
            $solrResults = $this->documentRepository->findSolrByCollection(/** @scrutinizer ignore-type */ '', $this->settings, $searchParams, $listedMetadata);
Loading history...
92
        }
93
94
        // Pagination of Results: Pass the currentPage to the fluid template to calculate current index of search result.
95
        $widgetPage = $this->getParametersSafely('@widget_0');
96
        if (empty($widgetPage)) {
97
            $widgetPage = ['currentPage' => 1];
98
        }
99
100
        $documents = $solrResults['documents'] ? : [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $solrResults does not seem to be defined for all execution paths leading up to this point.
Loading history...
101
        //$this->view->assign('metadata', $sortableMetadata);
102
        $this->view->assign('documents', $documents);
103
        $this->view->assign('widgetPage', $widgetPage);
104
        $this->view->assign('lastSearch', $searchParams);
105
106
        $this->view->assign('listedMetadata', $listedMetadata);
107
        $this->view->assign('sortableMetadata', $sortableMetadata);
108
109
        // ABTODO: facets and extended search might fail
110
        // Add the facets menu
111
        $this->addFacetsMenu();
112
113
        // Get additional fields for extended search.
114
        $this->addExtendedSearch();
115
    }
116
117
    /**
118
     * Adds the current document's UID or parent ID to the search form
119
     *
120
     * @access protected
121
     *
122
     * @return string HTML input fields with current document's UID
123
     */
124
    protected function addCurrentDocument()
125
    {
126
        // Load current list object.
127
        $list = GeneralUtility::makeInstance(DocumentList::class);
128
        // Load current document.
129
        if (
130
            !empty($this->requestData['id'])
131
            && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->requestData['id'])
132
        ) {
133
            $this->loadDocument($this->requestData);
134
            // Get document's UID
135
            if ($this->document) {
136
                $this->view->assign('DOCUMENT_ID', $this->document->getUid());
137
            }
138
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
139
            // Get document's UID from search metadata.
140
            // The string may be e.g. "{!join from=uid to=partof}uid:{!join from=uid to=partof}uid:2" OR {!join from=uid to=partof}uid:2 OR uid:2"
141
            // or "collection_faceting:("Some Collection Title")"
142
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
143
                if (($lastUidPos = strrpos($facet['query'], 'uid:')) !== false) {
144
                    $facetKeyVal = explode(':', substr($facet['query'], $lastUidPos));
145
                    if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($facetKeyVal[1])) {
146
                        $documentId = (int) $facetKeyVal[1];
147
                    }
148
                }
149
            }
150
            if (!empty($documentId)) {
151
                $this->view->assign('DOCUMENT_ID', $documentId);
152
            }
153
        }
154
    }
155
156
157
    /**
158
     * Adds the current collection's UID to the search form
159
     *
160
     * @access protected
161
     *
162
     * @return string HTML input fields with current document's UID and parent ID
163
     */
164
    protected function addCurrentCollection()
165
    {
166
        // Load current collection.
167
        $list = GeneralUtility::makeInstance(DocumentList::class);
168
        if (
169
            !empty($list->metadata['options']['source'])
170
            && $list->metadata['options']['source'] == 'collection'
171
        ) {
172
            $this->view->assign('COLLECTION_ID', $list->metadata['options']['select']);
173
            // Get collection's UID.
174
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
175
            // Get collection's UID from search metadata.
176
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
177
                $facetKeyVal = explode(':', $facet['query'], 2);
178
                if (
179
                    $facetKeyVal[0] == 'collection_faceting'
180
                    && !strpos($facetKeyVal[1], '" OR "')
181
                ) {
182
                    $collectionId = Helper::getUidFromIndexName(trim($facetKeyVal[1], '(")'), 'tx_dlf_collections');
183
                }
184
            }
185
            $this->view->assign('COLLECTION_ID', $collectionId);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $collectionId does not seem to be defined for all execution paths leading up to this point.
Loading history...
186
        }
187
    }
188
189
    /**
190
     * Adds the facets menu to the search form
191
     *
192
     * @access protected
193
     *
194
     * @return string HTML output of facets menu
195
     */
196
    protected function addFacetsMenu()
197
    {
198
        // Check for typoscript configuration to prevent fatal error.
199
        if (empty($this->settings['facetsConf'])) {
200
            $this->logger->warning('Incomplete plugin configuration');
201
            return '';
202
        }
203
        // Quit without doing anything if no facets are selected.
204
        if (empty($this->settings['facets']) && empty($this->settings['facetCollections'])) {
205
            return '';
206
        }
207
208
        // Get facets from plugin configuration.
209
        $facets = [];
210
        foreach (GeneralUtility::trimExplode(',', $this->settings['facets'], true) as $facet) {
211
            $facets[$facet . '_faceting'] = Helper::translate($facet, 'tx_dlf_metadata', $this->settings['storagePid']);
212
        }
213
214
        $this->view->assign('facetsMenu', $this->makeFacetsMenuArray($facets));
215
    }
216
217
    /**
218
     * This builds a menu array for HMENU
219
     *
220
     * @access public
221
     *
222
     * @param string $content: The PlugIn content
223
     * @param array $conf: The PlugIn configuration
224
     *
225
     * @return array HMENU array
226
     */
227
    public function makeFacetsMenuArray($facets)
228
    {
229
        $menuArray = [];
230
        // Set default value for facet search.
231
        $search = [
232
            'query' => '*',
233
            'params' => [
234
                'component' => [
235
                    'facetset' => [
236
                        'facet' => []
237
                    ]
238
                ]
239
            ]
240
        ];
241
        // Extract query and filter from last search.
242
        $list = GeneralUtility::makeInstance(DocumentList::class);
243
        if (!empty($list->metadata['options']['source'])) {
244
            if ($list->metadata['options']['source'] == 'search') {
245
                $search['query'] = $list->metadata['options']['select'];
246
            }
247
            $search['params'] = $list->metadata['options']['params'];
248
        }
249
        // Get applicable facets.
250
        $solr = Solr::getInstance($this->settings['solrcore']);
251
        if (!$solr->ready) {
252
            $this->logger->error('Apache Solr not available');
253
            return [];
254
        }
255
        // Set needed parameters for facet search.
256
        if (empty($search['params']['filterquery'])) {
257
            $search['params']['filterquery'] = [];
258
        }
259
260
        foreach (array_keys($facets) as $field) {
261
            $search['params']['component']['facetset']['facet'][] = [
262
                'type' => 'field',
263
                'key' => $field,
264
                'field' => $field,
265
                'limit' => $this->settings['limitFacets'],
266
                'sort' => isset($this->settings['sortingFacets']) ? $this->settings['sortingFacets'] : 'count'
267
            ];
268
        }
269
270
        // Set additional query parameters.
271
        $search['params']['start'] = 0;
272
        $search['params']['rows'] = 0;
273
        // Set query.
274
        $search['params']['query'] = $search['query'];
275
        // Perform search.
276
        $selectQuery = $solr->service->createSelect($search['params']);
277
        $results = $solr->service->select($selectQuery);
278
        $facet = $results->getFacetSet();
279
280
        $facetCollectionArray = [];
281
282
        // replace everything expect numbers and comma
283
        $facetCollections = preg_replace('/[^0-9,]/', '', $this->settings['facetCollections']);
284
285
        if (!empty($facetCollections)) {
286
            $collections = $this->collectionRepository->findCollectionsBySettings(['collections' => $facetCollections]);
287
288
            /** @var Collection $collection */
289
            foreach ($collections as $collection) {
290
                $facetCollectionArray[] = $collection->getIndexName();
291
            }
292
        }
293
294
        // Process results.
295
        if ($facet) {
296
            foreach ($facet as $field => $values) {
297
                $entryArray = [];
298
                $entryArray['title'] = htmlspecialchars($facets[$field]);
299
                $entryArray['count'] = 0;
300
                $entryArray['_OVERRIDE_HREF'] = '';
301
                $entryArray['doNotLinkIt'] = 1;
302
                $entryArray['ITEM_STATE'] = 'NO';
303
                // Count number of facet values.
304
                $i = 0;
305
                foreach ($values as $value => $count) {
306
                    if ($count > 0) {
307
                        // check if facet collection configuration exists
308
                        if (!empty($this->settings['facetCollections'])) {
309
                            if ($field == "collection_faceting" && !in_array($value, $facetCollectionArray)) {
310
                                continue;
311
                            }
312
                        }
313
                        $entryArray['count']++;
314
                        if ($entryArray['ITEM_STATE'] == 'NO') {
315
                            $entryArray['ITEM_STATE'] = 'IFSUB';
316
                        }
317
                        $entryArray['_SUB_MENU'][] = $this->getFacetsMenuEntry($field, $value, $count, $search, $entryArray['ITEM_STATE']);
318
                        if (++$i == $this->settings['limit']) {
319
                            break;
320
                        }
321
                    } else {
322
                        break;
323
                    }
324
                }
325
                $menuArray[] = $entryArray;
326
            }
327
        }
328
        return $menuArray;
329
    }
330
331
    /**
332
     * Creates an array for a HMENU entry of a facet value.
333
     *
334
     * @access protected
335
     *
336
     * @param string $field: The facet's index_name
337
     * @param string $value: The facet's value
338
     * @param int $count: Number of hits for this facet
339
     * @param array $search: The parameters of the current search query
340
     * @param string &$state: The state of the parent item
341
     *
342
     * @return array The array for the facet's menu entry
343
     */
344
    protected function getFacetsMenuEntry($field, $value, $count, $search, &$state)
345
    {
346
        $entryArray = [];
347
        // Translate value.
348
        if ($field == 'owner_faceting') {
349
            // Translate name of holding library.
350
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['storagePid']));
351
        } elseif ($field == 'type_faceting') {
352
            // Translate document type.
353
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['storagePid']));
354
        } elseif ($field == 'collection_faceting') {
355
            // Translate name of collection.
356
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->settings['storagePid']));
357
        } elseif ($field == 'language_faceting') {
358
            // Translate ISO 639 language code.
359
            $entryArray['title'] = htmlspecialchars(Helper::getLanguageName($value));
360
        } else {
361
            $entryArray['title'] = htmlspecialchars($value);
362
        }
363
        $entryArray['count'] = $count;
364
        $entryArray['doNotLinkIt'] = 0;
365
        // Check if facet is already selected.
366
        $queryColumn = array_column($search['params']['filterquery'], 'query');
367
        $index = array_search($field . ':("' . Solr::escapeQuery($value) . '")', $queryColumn);
368
        if ($index !== false) {
369
            // Facet is selected, thus remove it from filter.
370
            unset($queryColumn[$index]);
371
            $queryColumn = array_values($queryColumn);
372
            $entryArray['ITEM_STATE'] = 'CUR';
373
            $state = 'ACTIFSUB';
374
            //Reset facets
375
            if ($this->settings['resetFacets']) {
376
                //remove ($count) for selected facet in template
377
                $entryArray['count'] = false;
378
                //build link to delete selected facet
379
                $uri = $this->uriBuilder->reset()
380
                    ->setTargetPageUid($GLOBALS['TSFE']->id)
381
                    ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
382
                    ->setAddQueryString(true)
383
                    ->build();
384
                $entryArray['_OVERRIDE_HREF'] = $uri;
385
                $entryArray['title'] = sprintf(LocalizationUtility::translate('search.resetFacet', 'dlf'), $entryArray['title']);
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...rch.resetFacet', 'dlf') can also be of type null; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

385
                $entryArray['title'] = sprintf(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.resetFacet', 'dlf'), $entryArray['title']);
Loading history...
386
            }
387
        } else {
388
            // Facet is not selected, thus add it to filter.
389
            $queryColumn[] = $field . ':("' . Solr::escapeQuery($value) . '")';
390
            $entryArray['ITEM_STATE'] = 'NO';
391
        }
392
        $uri = $this->uriBuilder->reset()
393
            ->setTargetPageUid($GLOBALS['TSFE']->id)
394
            ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
395
            ->setArgumentPrefix('tx_dlf')
396
            ->build();
397
        $entryArray['_OVERRIDE_HREF'] = $uri;
398
399
        return $entryArray;
400
    }
401
402
    /**
403
     * Returns the extended search form and adds the JS files necessary for extended search.
404
     *
405
     * @access protected
406
     *
407
     * @return string The extended search form or an empty string
408
     */
409
    protected function addExtendedSearch()
410
    {
411
        // Quit without doing anything if no fields for extended search are selected.
412
        if (
413
            empty($this->settings['extendedSlotCount'])
414
            || empty($this->settings['extendedFields'])
415
        ) {
416
            return '';
417
        }
418
        // Get operator options.
419
        $operatorOptions = [];
420
        foreach (['AND', 'OR', 'NOT'] as $operator) {
421
            $operatorOptions[$operator] = htmlspecialchars(LocalizationUtility::translate('search.' . $operator, 'dlf'));
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...h.' . $operator, 'dlf') can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

421
            $operatorOptions[$operator] = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.' . $operator, 'dlf'));
Loading history...
422
        }
423
        // Get field selector options.
424
        $fieldSelectorOptions = [];
425
        $searchFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
426
        foreach ($searchFields as $searchField) {
427
            $fieldSelectorOptions[$searchField] = Helper::translate($searchField, 'tx_dlf_metadata', $this->settings['storagePid']);
428
        }
429
        $slotCountArray = [];
430
        for ($i = 0; $i < $this->settings['extendedSlotCount']; $i++) {
431
            $slotCountArray[] = $i;
432
        }
433
434
        $this->view->assign('extendedSlotCount', $slotCountArray);
435
        $this->view->assign('extendedFields', $this->settings['extendedFields']);
436
        $this->view->assign('operators', $operatorOptions);
437
        $this->view->assign('searchFields', $fieldSelectorOptions);
438
    }
439
}
440