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 (#692)
by Alexander
03:15
created

SearchController::mainAction()   C

Complexity

Conditions 12
Paths 17

Size

Total Lines 42
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 16
Bugs 0 Features 0
Metric Value
eloc 24
c 16
b 0
f 0
dl 0
loc 42
rs 6.9666
cc 12
nc 17
nop 0

How to fix   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\Document;
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\Core\Configuration\ExtensionConfiguration;
20
use TYPO3\CMS\Core\Database\Connection;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
24
class SearchController extends AbstractController
25
{
26
    public $prefixId = 'tx_dlf';
27
    public $extKey = 'dlf';
28
29
    /**
30
     * Search action
31
     */
32
    public function searchAction()
33
    {
34
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
35
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
36
37
        $this->extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get($this->extKey);
38
39
        // Build label for result list.
40
        $label = htmlspecialchars($this->pi_getLL('search', ''));
0 ignored issues
show
Unused Code introduced by
The call to Kitodo\Dlf\Controller\SearchController::pi_getLL() has too many arguments starting with ''. ( Ignorable by Annotation )

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

40
        $label = htmlspecialchars($this->/** @scrutinizer ignore-call */ pi_getLL('search', ''));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
41
        if (!empty($requestData['query'])) {
42
            $label .= htmlspecialchars(sprintf($this->pi_getLL('for', ''), trim($requestData['query'])));
43
        }
44
        // Prepare query parameters.
45
        $params = [];
46
        $matches = [];
47
        // Set search query.
48
        if (
49
            (!empty($this->settings['fulltext']) && !empty($requestData['fulltext']))
50
            || preg_match('/fulltext:\((.*)\)/', trim($requestData['query']), $matches)
51
        ) {
52
            // If the query already is a fulltext query e.g using the facets
53
            $requestData['query'] = empty($matches[1]) ? $requestData['query'] : $matches[1];
54
            // Search in fulltext field if applicable. Query must not be empty!
55
            if (!empty($requestData['query'])) {
56
                $query = 'fulltext:(' . Solr::escapeQuery(trim($requestData['query'])) . ')';
57
            }
58
        } else {
59
            // Retain given search field if valid.
60
            $query = Solr::escapeQueryKeepField(trim($requestData['query']), $this->settings['pages']);
61
        }
62
        // Add extended search query.
63
        if (
64
            !empty($requestData['extQuery'])
65
            && is_array($requestData['extQuery'])
66
        ) {
67
            $allowedOperators = ['AND', 'OR', 'NOT'];
68
            $allowedFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
69
            $numberOfExtQueries = count($requestData['extQuery']);
70
            for ($i = 0; $i < $numberOfExtQueries; $i++) {
71
                if (!empty($requestData['extQuery'][$i])) {
72
                    if (
73
                        in_array($requestData['extOperator'][$i], $allowedOperators)
74
                        && in_array($requestData['extField'][$i], $allowedFields)
75
                    ) {
76
                        if (!empty($query)) {
77
                            $query .= ' ' . $requestData['extOperator'][$i] . ' ';
78
                        }
79
                        $query .= Indexer::getIndexFieldName($requestData['extField'][$i], $this->settings['pages']) . ':(' . Solr::escapeQuery($requestData['extQuery'][$i]) . ')';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $query does not seem to be defined for all execution paths leading up to this point.
Loading history...
80
                    }
81
                }
82
            }
83
        }
84
        // Add filter query for faceting.
85
        if (!empty($requestData['fq'])) {
86
            foreach ($requestData['fq'] as $filterQuery) {
87
                $params['filterquery'][]['query'] = $filterQuery;
88
            }
89
        }
90
91
        // Add filter query for in-document searching.
92
        if (
93
            $this->settings['searchIn'] == 'document'
94
            || $this->settings['searchIn'] == 'all'
95
        ) {
96
            if (
97
                !empty($requestData['id'])
98
                && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($requestData['id'])
99
            ) {
100
                // Search in document and all subordinates (valid for up to three levels of hierarchy).
101
                $params['filterquery'][]['query'] = '_query_:"{!join from=uid to=partof}uid:{!join from=uid to=partof}uid:' . $requestData['id'] . '"' .
102
                    ' OR {!join from=uid to=partof}uid:' . $requestData['id'] .
103
                    ' OR uid:' . $requestData['id'];
104
                $label .= htmlspecialchars(sprintf($this->pi_getLL('in', ''), Document::getTitle($requestData['id'])));
105
            }
106
        }
107
        // Add filter query for in-collection searching.
108
        if (
109
            $this->settings['searchIn'] == 'collection'
110
            || $this->settings['searchIn'] == 'all'
111
        ) {
112
            if (
113
                !empty($requestData['collection'])
114
                && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($requestData['collection'])
115
            ) {
116
                $index_name = Helper::getIndexNameFromUid($requestData['collection'], 'tx_dlf_collections', $this->settings['pages']);
117
                $params['filterquery'][]['query'] = 'collection_faceting:("' . Solr::escapeQuery($index_name) . '")';
118
                $label .= sprintf($this->pi_getLL('in', '', true), Helper::translate($index_name, 'tx_dlf_collections', $this->settings['pages']));
119
            }
120
        }
121
        // Add filter query for collection restrictions.
122
        if ($this->settings['collections']) {
123
            $collIds = explode(',', $this->settings['collections']);
124
            $collIndexNames = [];
125
            foreach ($collIds as $collId) {
126
                $collIndexNames[] = Solr::escapeQuery(Helper::getIndexNameFromUid(intval($collId), 'tx_dlf_collections', $this->settings['pages']));
127
            }
128
            // Last value is fake and used for distinction in $this->addCurrentCollection()
129
            $params['filterquery'][]['query'] = 'collection_faceting:("' . implode('" OR "', $collIndexNames) . '" OR "FakeValueForDistinction")';
130
        }
131
        // Set some query parameters.
132
        $params['query'] = !empty($query) ? $query : '*';
133
        $params['start'] = 0;
134
        $params['rows'] = 0;
135
        $params['sort'] = ['score' => 'desc'];
136
        // Instantiate search object.
137
        $solr = Solr::getInstance($this->settings['solrcore']);
138
        if (!$solr->ready) {
139
            $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

139
            $this->logger->/** @scrutinizer ignore-call */ 
140
                           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...
140
            $this->redirect('main', 'Search', NULL);
141
            //return $this->responseFactory->createHtmlResponse($this->view->render());
142
        }
143
        // Set search parameters.
144
        $solr->cPid = $this->settings['pages'];
145
        $solr->params = $params;
146
        // Perform search.
147
        $list = $solr->search();
148
        $list->metadata = [
149
            'label' => $label,
150
            'thumbnail' => '',
151
            'searchString' => $requestData['query'],
152
            'fulltextSearch' => (!empty($requestData['fulltext']) ? '1' : '0'),
153
            'options' => $list->metadata['options']
154
        ];
155
        $list->save();
156
        // Clean output buffer.
157
        ob_end_clean();
158
        $additionalParams = [];
159
        if (!empty($requestData['logicalPage'])) {
160
            $additionalParams['logicalPage'] = $requestData['logicalPage'];
161
        }
162
        // Jump directly to the page view, if there is only one result and it is configured
163
        if ($list->metadata['options']['numberOfHits'] == 1 && !empty($this->settings['showSingleResult'])) {
164
            $linkConf['parameter'] = $this->settings['targetPidPageView'];
165
            $additionalParams['id'] = $list->current()['uid'];
166
            $additionalParams['highlight_word'] = preg_replace('/\s\s+/', ';', $list->metadata['searchString']);
167
            $additionalParams['page'] = count($list[0]['subparts']) == 1 ? $list[0]['subparts'][0]['page'] : 1;
168
        } else {
169
            // Keep some plugin variables.
170
            $linkConf['parameter'] = $this->settings['targetPid'];
171
            if (!empty($requestData['order'])) {
172
                $additionalParams['order'] = $requestData['order'];
173
                $additionalParams['asc'] = !empty($requestData['asc']) ? '1' : '0';
174
            }
175
        }
176
        $linkConf['forceAbsoluteUrl'] = !empty($this->settings['forceAbsoluteUrl']) ? 1 : 0;
177
        $linkConf['forceAbsoluteUrl.']['scheme'] = !empty($this->settings['forceAbsoluteUrl']) && !empty($this->settings['forceAbsoluteUrlHttps']) ? 'https' : 'http';
178
        $linkConf['additionalParams'] = GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', true, false);
179
180
        $this->redirect('main', 'Search', NULL, NULL);
181
    }
182
183
    /**
184
     *
185
     * @return mixed
186
     * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException
187
     */
188
    public function mainAction()
189
    {
190
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
191
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
192
193
        // Quit without doing anything if required variables are not set.
194
        if (empty($this->settings['solrcore'])) {
195
            $this->logger->warning('Incomplete plugin configuration');
196
            return '';
197
        }
198
        if (!isset($requestData['query'])
199
            && empty($requestData['extQuery'])
200
        ) {
201
            // Extract query and filter from last search.
202
            $list = GeneralUtility::makeInstance(DocumentList::class);
203
            if (!empty($list->metadata['searchString'])) {
204
                if ($list->metadata['options']['source'] == 'search') {
205
                    $search['query'] = $list->metadata['searchString'];
206
                }
207
                $search['params'] = $list->metadata['options']['params'];
208
            }
209
210
            $this->view->assign('QUERY', (!empty($search['query']) ? htmlspecialchars($search['query']) : ''));
211
            $this->view->assign('FULLTEXT_SEARCH', $list->metadata['fulltextSearch']);
212
        } else {
213
            $this->view->assign('QUERY', (!empty($requestData['query']) ? htmlspecialchars($requestData['query']) : ''));
214
            $this->view->assign('FULLTEXT_SEARCH', $requestData['fulltext']);
215
        }
216
217
        $this->view->assign('FACETS_MENU', $this->addFacetsMenu());
218
219
        $this->addEncryptedCoreName();
220
221
        if ($this->settings['searchIn'] == 'collection' || $this->settings['searchIn'] == 'all') {
222
            $this->addCurrentCollection();
223
        }
224
        if ($this->settings['searchIn'] == 'document' || $this->settings['searchIn'] == 'all') {
225
            $this->addCurrentDocument($requestData);
226
        }
227
228
        // Get additional fields for extended search.
229
        $this->addExtendedSearch();
230
    }
231
232
    protected function pi_getLL($label)
233
    {
234
        return $GLOBALS['TSFE']->sL('LLL:EXT:dlf/Resources/Private/Language/Search.xml:' . $label);
235
    }
236
237
    /**
238
     * Adds the current document's UID or parent ID to the search form
239
     *
240
     * @access protected
241
     *
242
     * @return string HTML input fields with current document's UID
243
     */
244
    protected function addCurrentDocument($requestData)
245
    {
246
        // Load current list object.
247
        $list = GeneralUtility::makeInstance(DocumentList::class);
248
        // Load current document.
249
        if (
250
            !empty($requestData['id'])
251
            && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($requestData['id'])
252
        ) {
253
            $this->loadDocument();
0 ignored issues
show
Bug introduced by
The call to Kitodo\Dlf\Controller\Ab...troller::loadDocument() has too few arguments starting with requestData. ( Ignorable by Annotation )

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

253
            $this->/** @scrutinizer ignore-call */ 
254
                   loadDocument();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
254
            // Get document's UID
255
            if ($this->doc->ready) {
256
                $this->view->assign('DOCUMENT_ID', $this->doc->uid);
257
            }
258
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
259
            // Get document's UID from search metadata.
260
            // 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"
261
            // or "collection_faceting:("Some Collection Title")"
262
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
263
                if (($lastUidPos = strrpos($facet['query'], 'uid:')) !== false) {
264
                    $facetKeyVal = explode(':', substr($facet['query'], $lastUidPos));
265
                    if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($facetKeyVal[1])) {
266
                        $documentId = (int) $facetKeyVal[1];
267
                    }
268
                }
269
            }
270
            if (!empty($documentId)) {
271
                $this->view->assign('DOCUMENT_ID', $documentId);
272
            }
273
        }
274
    }
275
276
277
    /**
278
     * Adds the current collection's UID to the search form
279
     *
280
     * @access protected
281
     *
282
     * @return string HTML input fields with current document's UID and parent ID
283
     */
284
    protected function addCurrentCollection()
285
    {
286
        // Load current collection.
287
        $list = GeneralUtility::makeInstance(DocumentList::class);
288
        if (
289
            !empty($list->metadata['options']['source'])
290
            && $list->metadata['options']['source'] == 'collection'
291
        ) {
292
            $this->view->assign('COLLECTION_ID', $list->metadata['options']['select']);
293
            // Get collection's UID.
294
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
295
            // Get collection's UID from search metadata.
296
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
297
                $facetKeyVal = explode(':', $facet['query'], 2);
298
                if (
299
                    $facetKeyVal[0] == 'collection_faceting'
300
                    && !strpos($facetKeyVal[1], '" OR "')
301
                ) {
302
                    $collectionId = Helper::getUidFromIndexName(trim($facetKeyVal[1], '(")'), 'tx_dlf_collections');
303
                }
304
            }
305
            $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...
306
        }
307
    }
308
309
    /**
310
     * Adds the encrypted Solr core name to the search form
311
     *
312
     * @access protected
313
     *
314
     * @return string HTML input fields with encrypted core name and hash
315
     */
316
    protected function addEncryptedCoreName()
317
    {
318
        // Get core name.
319
        $name = Helper::getIndexNameFromUid($this->settings['solrcore'], 'tx_dlf_solrcores');
320
        // Encrypt core name.
321
        if (!empty($name)) {
322
            $name = Helper::encrypt($name);
323
        }
324
        // Add encrypted fields to search form.
325
        if ($name !== false) {
326
            $this->view->assign('ENCRYPTED_CORE_NAME', $name);
327
        }
328
    }
329
330
    /**
331
     * Adds the facets menu to the search form
332
     *
333
     * @access protected
334
     *
335
     * @return string HTML output of facets menu
336
     */
337
    protected function addFacetsMenu()
338
    {
339
        // Check for typoscript configuration to prevent fatal error.
340
        if (empty($this->settings['facetsConf'])) {
341
            $this->logger->warning('Incomplete plugin configuration');
342
            return '';
343
        }
344
        // Quit without doing anything if no facets are selected.
345
        if (empty($this->settings['facets']) && empty($this->settings['facetCollections'])) {
346
            return '';
347
        }
348
349
        // Get facets from plugin configuration.
350
        $facets = [];
351
        foreach (GeneralUtility::trimExplode(',', $this->settings['facets'], true) as $facet) {
352
            $facets[$facet . '_faceting'] = Helper::translate($facet, 'tx_dlf_metadata', $this->settings['pages']);
353
        }
354
355
        $this->view->assign('facetsMenu', $this->makeFacetsMenuArray($facets));
356
    }
357
358
    /**
359
     * This builds a menu array for HMENU
360
     *
361
     * @access public
362
     *
363
     * @param string $content: The PlugIn content
364
     * @param array $conf: The PlugIn configuration
365
     *
366
     * @return array HMENU array
367
     */
368
    public function makeFacetsMenuArray($facets)
369
    {
370
        $menuArray = [];
371
        // Set default value for facet search.
372
        $search = [
373
            'query' => '*',
374
            'params' => [
375
                'component' => [
376
                    'facetset' => [
377
                        'facet' => []
378
                    ]
379
                ]
380
            ]
381
        ];
382
        // Extract query and filter from last search.
383
        $list = GeneralUtility::makeInstance(DocumentList::class);
384
        if (!empty($list->metadata['options']['source'])) {
385
            if ($list->metadata['options']['source'] == 'search') {
386
                $search['query'] = $list->metadata['options']['select'];
387
            }
388
            $search['params'] = $list->metadata['options']['params'];
389
        }
390
        // Get applicable facets.
391
        $solr = Solr::getInstance($this->settings['solrcore']);
392
        if (!$solr->ready) {
393
            $this->logger->error('Apache Solr not available');
394
            return [];
395
        }
396
        // Set needed parameters for facet search.
397
        if (empty($search['params']['filterquery'])) {
398
            $search['params']['filterquery'] = [];
399
        }
400
401
        foreach (array_keys($facets) as $field) {
402
            $search['params']['component']['facetset']['facet'][] = [
403
                'type' => 'field',
404
                'key' => $field,
405
                'field' => $field,
406
                'limit' => $this->settings['limitFacets'],
407
                'sort' => isset($this->settings['sortingFacets']) ? $this->settings['sortingFacets'] : 'count'
408
            ];
409
        }
410
411
        // Set additional query parameters.
412
        $search['params']['start'] = 0;
413
        $search['params']['rows'] = 0;
414
        // Set query.
415
        $search['params']['query'] = $search['query'];
416
        // Perform search.
417
        $selectQuery = $solr->service->createSelect($search['params']);
418
        $results = $solr->service->select($selectQuery);
419
        $facet = $results->getFacetSet();
420
421
        $facetCollectionArray = [];
422
423
        // replace everything expect numbers and comma
424
        $facetCollections = preg_replace('/[^0-9,]/', '', $this->settings['facetCollections']);
425
426
        if (!empty($facetCollections)) {
427
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
428
                ->getQueryBuilderForTable('tx_dlf_collections');
429
430
            $result = $queryBuilder
431
                ->select('tx_dlf_collections.index_name AS index_name')
432
                ->from('tx_dlf_collections')
433
                ->where(
434
                    $queryBuilder->expr()->in(
435
                        'tx_dlf_collections.uid',
436
                        $queryBuilder->createNamedParameter(GeneralUtility::intExplode(',', $facetCollections), Connection::PARAM_INT_ARRAY)
437
                    )
438
                )
439
                ->execute();
440
441
            while ($collection = $result->fetch()) {
442
                $facetCollectionArray[] = $collection['index_name'];
443
            }
444
        }
445
446
        // Process results.
447
        foreach ($facet as $field => $values) {
448
            $entryArray = [];
449
            $entryArray['title'] = htmlspecialchars($facets[$field]);
450
            $entryArray['count'] = 0;
451
            $entryArray['_OVERRIDE_HREF'] = '';
452
            $entryArray['doNotLinkIt'] = 1;
453
            $entryArray['ITEM_STATE'] = 'NO';
454
            // Count number of facet values.
455
            $i = 0;
456
            foreach ($values as $value => $count) {
457
                if ($count > 0) {
458
                    // check if facet collection configuration exists
459
                    if (!empty($this->settings['facetCollections'])) {
460
                        if ($field == "collection_faceting" && !in_array($value, $facetCollectionArray)) {
461
                            continue;
462
                        }
463
                    }
464
                    $entryArray['count']++;
465
                    if ($entryArray['ITEM_STATE'] == 'NO') {
466
                        $entryArray['ITEM_STATE'] = 'IFSUB';
467
                    }
468
                    $entryArray['_SUB_MENU'][] = $this->getFacetsMenuEntry($field, $value, $count, $search, $entryArray['ITEM_STATE']);
469
                    if (++$i == $this->settings['limit']) {
470
                        break;
471
                    }
472
                } else {
473
                    break;
474
                }
475
            }
476
            $menuArray[] = $entryArray;
477
        }
478
        return $menuArray;
479
    }
480
481
    /**
482
     * Creates an array for a HMENU entry of a facet value.
483
     *
484
     * @access protected
485
     *
486
     * @param string $field: The facet's index_name
487
     * @param string $value: The facet's value
488
     * @param int $count: Number of hits for this facet
489
     * @param array $search: The parameters of the current search query
490
     * @param string &$state: The state of the parent item
491
     *
492
     * @return array The array for the facet's menu entry
493
     */
494
    protected function getFacetsMenuEntry($field, $value, $count, $search, &$state)
495
    {
496
        $entryArray = [];
497
        // Translate value.
498
        if ($field == 'owner_faceting') {
499
            // Translate name of holding library.
500
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['pages']));
501
        } elseif ($field == 'type_faceting') {
502
            // Translate document type.
503
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['pages']));
504
        } elseif ($field == 'collection_faceting') {
505
            // Translate name of collection.
506
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->settings['pages']));
507
        } elseif ($field == 'language_faceting') {
508
            // Translate ISO 639 language code.
509
            $entryArray['title'] = htmlspecialchars(Helper::getLanguageName($value));
510
        } else {
511
            $entryArray['title'] = htmlspecialchars($value);
512
        }
513
        $entryArray['count'] = $count;
514
        $entryArray['doNotLinkIt'] = 0;
515
        // Check if facet is already selected.
516
        $queryColumn = array_column($search['params']['filterquery'], 'query');
517
        $index = array_search($field . ':("' . Solr::escapeQuery($value) . '")', $queryColumn);
518
        if ($index !== false) {
519
            // Facet is selected, thus remove it from filter.
520
            unset($queryColumn[$index]);
521
            $queryColumn = array_values($queryColumn);
522
            $entryArray['ITEM_STATE'] = 'CUR';
523
            $state = 'ACTIFSUB';
524
            //Reset facets
525
            if ($this->settings['resetFacets']) {
526
                //remove ($count) for selected facet in template
527
                $entryArray['count'] = false;
528
                //build link to delete selected facet
529
                $uri = $this->uriBuilder->reset()
530
                    ->setTargetPageUid($GLOBALS['TSFE']->id)
531
                    ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
532
                    ->setAddQueryString(true)
533
                    ->build();
534
                $entryArray['_OVERRIDE_HREF'] = $uri;
535
                $entryArray['title'] = sprintf($this->pi_getLL('resetFacet', ''), $entryArray['title']);
0 ignored issues
show
Unused Code introduced by
The call to Kitodo\Dlf\Controller\SearchController::pi_getLL() has too many arguments starting with ''. ( Ignorable by Annotation )

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

535
                $entryArray['title'] = sprintf($this->/** @scrutinizer ignore-call */ pi_getLL('resetFacet', ''), $entryArray['title']);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
536
            }
537
        } else {
538
            // Facet is not selected, thus add it to filter.
539
            $queryColumn[] = $field . ':("' . Solr::escapeQuery($value) . '")';
540
            $entryArray['ITEM_STATE'] = 'NO';
541
        }
542
        $uri = $this->uriBuilder->reset()
543
            ->setTargetPageUid($GLOBALS['TSFE']->id)
544
            ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
545
            ->setArgumentPrefix('tx_dlf')
546
            ->build();
547
        $entryArray['_OVERRIDE_HREF'] = $uri;
548
549
        return $entryArray;
550
    }
551
552
    /**
553
     * Returns the extended search form and adds the JS files necessary for extended search.
554
     *
555
     * @access protected
556
     *
557
     * @return string The extended search form or an empty string
558
     */
559
    protected function addExtendedSearch()
560
    {
561
        // Quit without doing anything if no fields for extended search are selected.
562
        if (
563
            empty($this->settings['extendedSlotCount'])
564
            || empty($this->settings['extendedFields'])
565
        ) {
566
            return '';
567
        }
568
        // Get operator options.
569
        $operatorOptions = [];
570
        foreach (['AND', 'OR', 'NOT'] as $operator) {
571
            $operatorOptions[$operator] = htmlspecialchars($this->pi_getLL($operator, ''));
0 ignored issues
show
Unused Code introduced by
The call to Kitodo\Dlf\Controller\SearchController::pi_getLL() has too many arguments starting with ''. ( Ignorable by Annotation )

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

571
            $operatorOptions[$operator] = htmlspecialchars($this->/** @scrutinizer ignore-call */ pi_getLL($operator, ''));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
572
        }
573
        // Get field selector options.
574
        $fieldSelectorOptions = [];
575
        $searchFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
576
        foreach ($searchFields as $searchField) {
577
            $fieldSelectorOptions[$searchField] = Helper::translate($searchField, 'tx_dlf_metadata', $this->settings['pages']);
578
        }
579
        for ($i = 0; $i < $this->settings['extendedSlotCount']; $i++) {
580
            $slotCountArray[] = $i;
581
        }
582
583
        $this->view->assign('extendedSlotCount', $slotCountArray);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $slotCountArray does not seem to be defined for all execution paths leading up to this point.
Loading history...
584
        $this->view->assign('extendedFields', $this->settings['extendedFields']);
585
        $this->view->assign('operators', $operatorOptions);
586
        $this->view->assign('searchFields', $fieldSelectorOptions);
587
    }
588
}
589