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
07:57
created

SearchController   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 431
Duplicated Lines 0 %

Importance

Changes 24
Bugs 0 Features 0
Metric Value
eloc 189
c 24
b 0
f 0
dl 0
loc 431
rs 3.2
wmc 65

10 Methods

Rating   Name   Duplication   Size   Complexity  
A injectMetadataRepository() 0 3 1
A injectCollectionRepository() 0 3 1
A searchAction() 0 4 1
B mainAction() 0 60 10
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');
0 ignored issues
show
Unused Code introduced by
The assignment to $searchParams is dead and can be removed.
Loading history...
61
62
        // output is done by main action
63
//        $this->forward('main', null, null, ['searchParameter' => $searchParams]);
64
//        $this->forward('main', 'ListView', null, ['searchParameter' => $searchParams]);
65
    }
66
67
    /**
68
     * Main action
69
     *
70
     * @return void
71
     */
72
    public function mainAction()
73
    {
74
        // Quit without doing anything if required variables are not set.
75
        if (empty($this->settings['solrcore'])) {
76
            $this->logger->warning('Incomplete plugin configuration');
77
            return;
78
        }
79
80
        // if search was triggered, get search parameters from POST variables
81
        $searchParams = $this->getParametersSafely('searchParameter');
82
83
        // Pagination of Results: Pass the currentPage to the fluid template to calculate current index of search result.
84
        $widgetPage = $this->getParametersSafely('@widget_0');
85
        if (empty($widgetPage)) {
86
            $widgetPage = ['currentPage' => 1];
87
        }
88
89
        // If a targetPid is given, the results will be shown by ListView on the target page.
90
        if (!empty($this->settings['targetPid']) && !empty($searchParams)) {
91
            $this->redirect('main', 'ListView', null,
92
                [
93
                    'searchParameter' => $searchParams,
94
                    'widgetPage' => $widgetPage,
95
                    'solrcore' => $this->settings['solrcore']
96
                ], $this->settings['targetPid']
97
            );
98
        }
99
100
        // get results from search
101
        // find all documents from Solr
102
        $solrResults = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $solrResults is dead and can be removed.
Loading history...
103
        if (is_array($searchParams) && !empty($searchParams)) {
104
           $solrResults = $this->documentRepository->findSolrByCollection('', $this->settings, $searchParams, $listedMetadata);
0 ignored issues
show
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

104
           $solrResults = $this->documentRepository->findSolrByCollection(/** @scrutinizer ignore-type */ '', $this->settings, $searchParams, $listedMetadata);
Loading history...
Comprehensibility Best Practice introduced by
The variable $listedMetadata seems to be never defined.
Loading history...
105
106
           // get all sortable metadata records
107
            $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

107
            /** @scrutinizer ignore-call */ 
108
            $sortableMetadata = $this->metadataRepository->findByIsSortable(true);
Loading history...
108
109
            // get all metadata records to be shown in results
110
            $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

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

402
                $entryArray['title'] = sprintf(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.resetFacet', 'dlf'), $entryArray['title']);
Loading history...
403
            }
404
        } else {
405
            // Facet is not selected, thus add it to filter.
406
            $queryColumn[] = $field . ':("' . Solr::escapeQuery($value) . '")';
407
            $entryArray['ITEM_STATE'] = 'NO';
408
        }
409
        $uri = $this->uriBuilder->reset()
410
            ->setTargetPageUid($GLOBALS['TSFE']->id)
411
            ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
412
            ->setArgumentPrefix('tx_dlf')
413
            ->build();
414
        $entryArray['_OVERRIDE_HREF'] = $uri;
415
416
        return $entryArray;
417
    }
418
419
    /**
420
     * Returns the extended search form and adds the JS files necessary for extended search.
421
     *
422
     * @access protected
423
     *
424
     * @return string The extended search form or an empty string
425
     */
426
    protected function addExtendedSearch()
427
    {
428
        // Quit without doing anything if no fields for extended search are selected.
429
        if (
430
            empty($this->settings['extendedSlotCount'])
431
            || empty($this->settings['extendedFields'])
432
        ) {
433
            return '';
434
        }
435
        // Get operator options.
436
        $operatorOptions = [];
437
        foreach (['AND', 'OR', 'NOT'] as $operator) {
438
            $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

438
            $operatorOptions[$operator] = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.' . $operator, 'dlf'));
Loading history...
439
        }
440
        // Get field selector options.
441
        $fieldSelectorOptions = [];
442
        $searchFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
443
        foreach ($searchFields as $searchField) {
444
            $fieldSelectorOptions[$searchField] = Helper::translate($searchField, 'tx_dlf_metadata', $this->settings['storagePid']);
445
        }
446
        $slotCountArray = [];
447
        for ($i = 0; $i < $this->settings['extendedSlotCount']; $i++) {
448
            $slotCountArray[] = $i;
449
        }
450
451
        $this->view->assign('extendedSlotCount', $slotCountArray);
452
        $this->view->assign('extendedFields', $this->settings['extendedFields']);
453
        $this->view->assign('operators', $operatorOptions);
454
        $this->view->assign('searchFields', $fieldSelectorOptions);
455
    }
456
}
457