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
Push — master ( 5fcc99...e2fc25 )
by
unknown
03:23
created

SearchController::processResults()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 36
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 24
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 36
rs 7.6666

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
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Controller;
14
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Indexer;
17
use Kitodo\Dlf\Common\Solr;
18
use TYPO3\CMS\Core\Core\Environment;
19
use TYPO3\CMS\Core\Information\Typo3Version;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
22
use Kitodo\Dlf\Domain\Repository\MetadataRepository;
23
24
/**
25
 * Controller class for the plugin 'Search'.
26
 *
27
 * @author Sebastian Meyer <[email protected]>
28
 * @author Henrik Lochmann <[email protected]>
29
 * @author Frank Ulrich Weber <[email protected]>
30
 * @author Alexander Bigga <[email protected]>
31
 * @package TYPO3
32
 * @subpackage dlf
33
 * @access public
34
 */
35
class SearchController extends AbstractController
36
{
37
    /**
38
     * @var CollectionRepository
39
     */
40
    protected $collectionRepository;
41
42
    /**
43
     * @param CollectionRepository $collectionRepository
44
     */
45
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
46
    {
47
        $this->collectionRepository = $collectionRepository;
48
    }
49
50
    /**
51
     * @var MetadataRepository
52
     */
53
    protected $metadataRepository;
54
55
    /**
56
     * @param MetadataRepository $metadataRepository
57
     */
58
    public function injectMetadataRepository(MetadataRepository $metadataRepository)
59
    {
60
        $this->metadataRepository = $metadataRepository;
61
    }
62
63
    /**
64
     * @var array $this->searchParams: The current search parameter
65
     * @access protected
66
     */
67
    protected $searchParams;
68
69
    /**
70
     * Search Action
71
     *
72
     * @return void
73
     */
74
    public function searchAction()
75
    {
76
        // if search was triggered, get search parameters from POST variables
77
        $this->searchParams = $this->getParametersSafely('searchParameter');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getParametersSafely('searchParameter') can also be of type string. However, the property $searchParams is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
78
79
        // output is done by main action
80
        $this->forward('main', null, null, ['searchParameter' => $this->searchParams]);
81
    }
82
83
    /**
84
     * Main action
85
     *
86
     * This shows the search form and optional the facets and extended search form.
87
     *
88
     * @return void
89
     */
90
    public function mainAction()
91
    {
92
        $listViewSearch = false;
93
        // Quit without doing anything if required variables are not set.
94
        if (empty($this->settings['solrcore'])) {
95
            $this->logger->warning('Incomplete plugin configuration');
96
            return;
97
        }
98
99
        // if search was triggered, get search parameters from POST variables
100
        $this->searchParams = $this->getParametersSafely('searchParameter');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getParametersSafely('searchParameter') can also be of type string. However, the property $searchParams is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
101
        // if search was triggered by the ListView plugin, get the parameters from GET variables
102
        $listRequestData = GeneralUtility::_GPmerged('tx_dlf_listview');
103
104
        if (isset($listRequestData['searchParameter']) && is_array($listRequestData['searchParameter'])) {
105
            $this->searchParams = array_merge($this->searchParams ?: [], $listRequestData['searchParameter']);
0 ignored issues
show
Bug introduced by
It seems like $this->searchParams ?: array() can also be of type string; however, parameter $arrays of array_merge() 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

105
            $this->searchParams = array_merge(/** @scrutinizer ignore-type */ $this->searchParams ?: [], $listRequestData['searchParameter']);
Loading history...
106
            $listViewSearch = true;
107
            $GLOBALS['TSFE']->fe_user->setKey('ses', 'search', $this->searchParams);
108
        }
109
110
        // sanitize date search input
111
        if (empty($this->searchParams['dateFrom']) && !empty($this->searchParams['dateTo'])) {
112
            $this->searchParams['dateFrom'] = '*';
113
        }
114
        if (empty($this->searchParams['dateTo']) && !empty($this->searchParams['dateFrom'])) {
115
            $this->searchParams['dateTo'] = 'NOW';
116
        }
117
        if ($this->searchParams['dateFrom'] > $this->searchParams['dateTo']) {
118
            $tmpDate = $this->searchParams['dateFrom'];
119
            $this->searchParams['dateFrom'] = $this->searchParams['dateTo'];
120
            $this->searchParams['dateTo'] = $tmpDate;
121
        }
122
123
        // Pagination of Results: Pass the currentPage to the fluid template to calculate current index of search result.
124
        $widgetPage = $this->getParametersSafely('@widget_0');
125
        if (empty($widgetPage)) {
126
            $widgetPage = ['currentPage' => 1];
127
        }
128
129
        // If a targetPid is given, the results will be shown by ListView on the target page.
130
        if (!empty($this->settings['targetPid']) && !empty($this->searchParams) && !$listViewSearch) {
131
            $this->redirect(
132
                'main',
133
                'ListView',
134
                null,
135
                [
136
                    'searchParameter' => $this->searchParams,
137
                    'widgetPage' => $widgetPage
138
                ],
139
                $this->settings['targetPid']
140
            );
141
        }
142
143
        // If no search has been executed, no variables habe to be prepared. An empty form will be shown.
144
        if (is_array($this->searchParams) && !empty($this->searchParams)) {
145
            // get all sortable metadata records
146
            $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

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

149
            /** @scrutinizer ignore-call */ 
150
            $listedMetadata = $this->metadataRepository->findByIsListed(true);
Loading history...
150
151
            $solrResults = null;
152
            $numResults = 0;
153
            // Do not execute the Solr search if used together with ListView plugin.
154
            if (!$listViewSearch) {
155
                $solrResults = $this->documentRepository->findSolrByCollection(null, $this->settings, $this->searchParams, $listedMetadata);
156
                $numResults = $solrResults->getNumFound();
157
            }
158
159
            $this->view->assign('documents', !empty($solrResults) ? $solrResults : []);
160
            $this->view->assign('numResults', $numResults);
161
            $this->view->assign('widgetPage', $widgetPage);
162
            $this->view->assign('lastSearch', $this->searchParams);
163
            $this->view->assign('listedMetadata', $listedMetadata);
164
            $this->view->assign('sortableMetadata', $sortableMetadata);
165
166
            // Add the facets menu
167
            $this->addFacetsMenu();
168
        }
169
170
        // Get additional fields for extended search.
171
        $this->addExtendedSearch();
172
173
        // Add the current document if present to fluid. This way, we can limit further searches to this document.
174
        if (isset($this->requestData['id'])) {
175
            $currentDocument = $this->documentRepository->findByUid($this->requestData['id']);
176
            $this->view->assign('currentDocument', $currentDocument);
177
        }
178
179
        // Add uHash parameter to suggest parameter to make a basic protection of this form.
180
        if ($this->settings['suggest']) {
181
            $this->view->assign('uHash', GeneralUtility::hmac((string) (new Typo3Version()) . Environment::getExtensionsPath(), 'SearchSuggest'));
182
        }
183
184
        $this->view->assign('viewData', $this->viewData);
185
    }
186
187
    /**
188
     * Adds the facets menu to the search form
189
     *
190
     * @access protected
191
     *
192
     * @return string HTML output of facets menu
193
     */
194
    protected function addFacetsMenu()
195
    {
196
        // Quit without doing anything if no facets are configured.
197
        if (empty($this->settings['facets']) && empty($this->settings['facetCollections'])) {
198
            return '';
199
        }
200
201
        // Get facets from plugin configuration.
202
        $facets = [];
203
        foreach (GeneralUtility::trimExplode(',', $this->settings['facets'], true) as $facet) {
204
            $facets[$facet . '_faceting'] = Helper::translate($facet, 'tx_dlf_metadata', $this->settings['storagePid']);
205
        }
206
207
        $this->view->assign('facetsMenu', $this->makeFacetsMenuArray($facets));
208
    }
209
210
    /**
211
     * This builds a menu array for HMENU
212
     *
213
     * @access public
214
     *
215
     * @param string $content: The PlugIn content
216
     * @param array $conf: The PlugIn configuration
217
     *
218
     * @return array HMENU array
219
     */
220
    public function makeFacetsMenuArray($facets)
221
    {
222
        // Set default value for facet search.
223
        $search = [
224
            'query' => '*:*',
225
            'params' => [
226
                'component' => [
227
                    'facetset' => [
228
                        'facet' => []
229
                    ]
230
                ]
231
            ]
232
        ];
233
234
        // Set needed parameters for facet search.
235
        if (empty($search['params']['filterquery'])) {
236
            $search['params']['filterquery'] = [];
237
        }
238
239
        $fields = Solr::getFields();
240
241
        // Set search query.
242
        $searchParams = $this->searchParams;
243
        if (
244
            (!empty($searchParams['fulltext']))
245
            || preg_match('/' . $fields['fulltext'] . ':\((.*)\)/', trim($searchParams['query']), $matches)
246
        ) {
247
            // If the query already is a fulltext query e.g using the facets
248
            $searchParams['query'] = empty($matches[1]) ? $searchParams['query'] : $matches[1];
249
            // Search in fulltext field if applicable. Query must not be empty!
250
            if (!empty($this->searchParams['query'])) {
251
                $search['query'] = $fields['fulltext'] . ':(' . Solr::escapeQuery(trim($searchParams['query'])) . ')';
252
            }
253
        } else {
254
            // Retain given search field if valid.
255
            if (!empty($searchParams['query'])) {
256
                $search['query'] = Solr::escapeQueryKeepField(trim($searchParams['query']), $this->settings['storagePid']);
257
            }
258
        }
259
260
        $collectionsQuery = $this->addCollectionsQuery($searchParams['query']);
261
        if (!empty($collectionsQuery)) {
262
            $search['params']['filterquery'][]['query'] = $collectionsQuery;
263
        }
264
265
        // add filter query for date search
266
        if (!empty($this->searchParams['dateFrom']) && !empty($this->searchParams['dateTo'])) {
267
            // combine dateFrom and dateTo into filterquery as range search
268
            $search['params']['filterquery'][]['query'] = '{!join from=' . $fields['uid'] . ' to=' . $fields['uid'] . '}' . $fields['date'] . ':[' . $this->searchParams['dateFrom'] . ' TO ' . $this->searchParams['dateTo'] . ']';
269
        }
270
271
        // Add extended search query.
272
        if (
273
            !empty($searchParams['extQuery'])
274
            && is_array($searchParams['extQuery'])
275
        ) {
276
            // If the search query is already set by the simple search field, we have to reset it.
277
            $search['query'] = '';
278
            $allowedOperators = ['AND', 'OR', 'NOT'];
279
            $numberOfExtQueries = count($searchParams['extQuery']);
280
            for ($i = 0; $i < $numberOfExtQueries; $i++) {
281
                if (!empty($searchParams['extQuery'][$i])) {
282
                    if (
283
                        in_array($searchParams['extOperator'][$i], $allowedOperators)
284
                    ) {
285
                        if (!empty($search['query'])) {
286
                            $search['query'] .= ' ' . $searchParams['extOperator'][$i] . ' ';
287
                        }
288
                        $search['query'] .= Indexer::getIndexFieldName($searchParams['extField'][$i], $this->settings['storagePid']) . ':(' . Solr::escapeQuery($searchParams['extQuery'][$i]) . ')';
289
                    }
290
                }
291
            }
292
        }
293
294
        if (isset($this->searchParams['fq']) && is_array($this->searchParams['fq'])) {
295
            foreach ($this->searchParams['fq'] as $fq) {
296
                $search['params']['filterquery'][]['query'] = $fq;
297
            }
298
        }
299
300
        // Get applicable facets.
301
        $solr = Solr::getInstance($this->settings['solrcore']);
302
        if (!$solr->ready) {
303
            $this->logger->error('Apache Solr not available');
304
            return [];
305
        }
306
307
        foreach (array_keys($facets) as $field) {
308
            $search['params']['component']['facetset']['facet'][] = [
309
                'type' => 'field',
310
                'mincount' => '1',
311
                'key' => $field,
312
                'field' => $field,
313
                'limit' => $this->settings['limitFacets'],
314
                'sort' => isset($this->settings['sortingFacets']) ? $this->settings['sortingFacets'] : 'count'
315
            ];
316
        }
317
318
        // Set additional query parameters.
319
        $search['params']['start'] = 0;
320
        $search['params']['rows'] = 0;
321
        // Set query.
322
        $search['params']['query'] = $search['query'];
323
        // Perform search.
324
        $selectQuery = $solr->service->createSelect($search['params']);
325
        // check for solr response
326
        $solrRequest = $solr->service->createRequest($selectQuery);
327
        $response = $solr->service->executeRequest($solrRequest);
328
        // return empty facet on solr error
329
        if ($response->getStatusCode() == "400") {
330
            return [];
331
        }
332
        $results = $solr->service->select($selectQuery);
333
        $facet = $results->getFacetSet();
334
335
        $facetCollectionArray = [];
336
337
        // replace everything expect numbers and comma
338
        $facetCollections = preg_replace('/[^\d,]/', '', $this->settings['facetCollections']);
339
340
        if (!empty($facetCollections)) {
341
            $collections = $this->collectionRepository->findCollectionsBySettings(['collections' => $facetCollections]);
342
343
            /** @var Collection $collection */
344
            foreach ($collections as $collection) {
345
                $facetCollectionArray[] = $collection->getIndexName();
346
            }
347
        }
348
349
        return $this->processResults($facet, $facetCollectionArray, $search);
0 ignored issues
show
Bug introduced by
It seems like $facet can also be of type Solarium\Component\Result\FacetSet; however, parameter $facet of Kitodo\Dlf\Controller\Se...oller::processResults() 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

349
        return $this->processResults(/** @scrutinizer ignore-type */ $facet, $facetCollectionArray, $search);
Loading history...
350
    }
351
352
    /**
353
     * Add the collection query string, if the collections are given.
354
     *
355
     * @access private
356
     * 
357
     * @param string $query The current query
358
     *
359
     * @return string The collection query string
360
     */
361
    private function addCollectionsQuery($query) {
362
        // if collections are given, we prepare the collections query string
363
        // extract collections from collection parameter
364
        $collections = null;
365
        if ($this->searchParams['collection']) {
366
            foreach (explode(',', $this->searchParams['collection']) as $collectionEntry) {
367
                $collections[] = $this->collectionRepository->findByUid($collectionEntry);
0 ignored issues
show
Bug introduced by
$collectionEntry of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Extbase\Persis...Repository::findByUid(). ( Ignorable by Annotation )

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

367
                $collections[] = $this->collectionRepository->findByUid(/** @scrutinizer ignore-type */ $collectionEntry);
Loading history...
368
            }
369
        }
370
        if ($collections) {
0 ignored issues
show
introduced by
$collections is of type null, thus it always evaluated to false.
Loading history...
371
            $collectionsQueryString = '';
372
            $virtualCollectionsQueryString = '';
373
            foreach ($collections as $collectionEntry) {
374
                // check for virtual collections query string
375
                if ($collectionEntry->getIndexSearch()) {
376
                    $virtualCollectionsQueryString .= empty($virtualCollectionsQueryString) ? '(' . $collectionEntry->getIndexSearch() . ')' : ' OR (' . $collectionEntry->getIndexSearch() . ')';
377
                } else {
378
                    $collectionsQueryString .= empty($collectionsQueryString) ? '"' . $collectionEntry->getIndexName() . '"' : ' OR "' . $collectionEntry->getIndexName() . '"';
379
                }
380
            }
381
382
            // distinguish between simple collection browsing and actual searching within the collection(s)
383
            if (!empty($collectionsQueryString)) {
384
                if (empty($query)) {
385
                    $collectionsQueryString = '(collection_faceting:(' . $collectionsQueryString . ') AND toplevel:true AND partof:0)';
386
                } else {
387
                    $collectionsQueryString = '(collection_faceting:(' . $collectionsQueryString . '))';
388
                }
389
            }
390
391
            // virtual collections might query documents that are neither toplevel:true nor partof:0 and need to be searched separately
392
            if (!empty($virtualCollectionsQueryString)) {
393
                $virtualCollectionsQueryString = '(' . $virtualCollectionsQueryString . ')';
394
            }
395
396
            // combine both querystrings into a single filterquery via OR if both are given, otherwise pass either of those
397
            return implode(" OR ", array_filter([$collectionsQueryString, $virtualCollectionsQueryString]));
398
        }
399
        return "";
400
    }
401
402
    /**
403
     * Creates an array for a HMENU entry of a facet value.
404
     *
405
     * @access private
406
     *
407
     * @param string $field: The facet's index_name
408
     * @param string $value: The facet's value
409
     * @param int $count: Number of hits for this facet
410
     * @param array $search: The parameters of the current search query
411
     * @param string &$state: The state of the parent item
412
     *
413
     * @return array The array for the facet's menu entry
414
     */
415
    private function getFacetsMenuEntry($field, $value, $count, $search, &$state)
416
    {
417
        $entryArray = [];
418
        $entryArray['title'] = $this->translateValue($field, $value);
419
        $entryArray['count'] = $count;
420
        $entryArray['doNotLinkIt'] = 0;
421
        // Check if facet is already selected.
422
        $queryColumn = array_column($search['params']['filterquery'], 'query');
423
        $index = array_search($field . ':("' . Solr::escapeQuery($value) . '")', $queryColumn);
424
        if ($index !== false) {
425
            // Facet is selected, thus remove it from filter.
426
            unset($queryColumn[$index]);
427
            $queryColumn = array_values($queryColumn);
428
            $entryArray['ITEM_STATE'] = 'CUR';
429
            $state = 'ACTIFSUB';
430
            // Reset facets
431
            if ($this->settings['resetFacets']) {
432
                $entryArray['resetFacet'] = true;
433
                $entryArray['queryColumn'] = $queryColumn;
434
            }
435
        } else {
436
            // Facet is not selected, thus add it to filter.
437
            $queryColumn[] = $field . ':("' . Solr::escapeQuery($value) . '")';
438
            $entryArray['ITEM_STATE'] = 'NO';
439
        }
440
        $entryArray['queryColumn'] = $queryColumn;
441
442
        return $entryArray;
443
    }
444
445
    /**
446
     * Process results.
447
     *
448
     * @access private
449
     *
450
     * @param array $facet
451
     * @param array $facetCollectionArray
452
     * @param array $search
453
     *
454
     * @return array menu array
455
     */
456
    private function processResults($facet, $facetCollectionArray, $search) {
457
        $menuArray = [];
458
459
        if ($facet) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $facet of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
460
            foreach ($facet as $field => $values) {
461
                $entryArray = [];
462
                $entryArray['field'] = substr($field, 0, strpos($field, '_faceting'));
463
                $entryArray['count'] = 0;
464
                $entryArray['_OVERRIDE_HREF'] = '';
465
                $entryArray['ITEM_STATE'] = 'NO';
466
                // Count number of facet values.
467
                $i = 0;
468
                foreach ($values as $value => $count) {
469
                    if ($count > 0) {
470
                        // check if facet collection configuration exists
471
                        if (!empty($this->settings['facetCollections'])) {
472
                            if ($field == "collection_faceting" && !in_array($value, $facetCollectionArray)) {
473
                                continue;
474
                            }
475
                        }
476
                        $entryArray['count']++;
477
                        if ($entryArray['ITEM_STATE'] == 'NO') {
478
                            $entryArray['ITEM_STATE'] = 'IFSUB';
479
                        }
480
                        $entryArray['_SUB_MENU'][] = $this->getFacetsMenuEntry($field, $value, $count, $search, $entryArray['ITEM_STATE']);
481
                        if (++$i == $this->settings['limit']) {
482
                            break;
483
                        }
484
                    } else {
485
                        break;
486
                    }
487
                }
488
                $menuArray[] = $entryArray;
489
            }
490
        }
491
        return $menuArray;
492
    }
493
494
    /**
495
     * Translates value depending on the index name.
496
     *
497
     * @param string $field: The facet's index_name
498
     * @param string $value: The facet's value
499
     *
500
     * @return string
501
     */
502
    private function translateValue($field, $value)
503
    {
504
        switch ($field) {
505
            case 'owner_faceting':
506
                // Translate name of holding library.
507
                return htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['storagePid']));
508
            case 'type_faceting':
509
                // Translate document type.
510
                return htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['storagePid']));
511
            case 'collection_faceting':
512
                // Translate name of collection.
513
                return htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->settings['storagePid']));
514
            case 'language_faceting':
515
                // Translate ISO 639 language code.
516
                return htmlspecialchars(Helper::getLanguageName($value));
517
            default:
518
                return htmlspecialchars($value);
519
        }
520
    }
521
522
    /**
523
     * Returns the extended search form and adds the JS files necessary for extended search.
524
     *
525
     * @access private
526
     *
527
     * @return string The extended search form or an empty string
528
     */
529
    private function addExtendedSearch()
530
    {
531
        // Quit without doing anything if no fields for extended search are selected.
532
        if (
533
            empty($this->settings['extendedSlotCount'])
534
            || empty($this->settings['extendedFields'])
535
        ) {
536
            return '';
537
        }
538
539
        // Get field selector options.
540
        $searchFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
541
542
        $slotCountArray = [];
543
        for ($i = 0; $i < $this->settings['extendedSlotCount']; $i++) {
544
            $slotCountArray[] = $i;
545
        }
546
547
        $this->view->assign('extendedSlotCount', $slotCountArray);
548
        $this->view->assign('extendedFields', $this->settings['extendedFields']);
549
        $this->view->assign('operators', ['AND', 'OR', 'NOT']);
550
        $this->view->assign('searchFields', $searchFields);
551
    }
552
}
553