Passed
Push — master ( 3ce2af...702ea2 )
by Timo
24:17
created

SuggestService::getSolrSuggestions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 13
cp 0
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\Domain\Search\Suggest;
4
5
/***************************************************************
6
 *  Copyright notice
7
 *
8
 *  (c) 2017 Franz Saris <[email protected]>
9
 *  All rights reserved
10
 *
11
 *  This script is part of the TYPO3 project. The TYPO3 project is
12
 *  free software; you can redistribute it and/or modify
13
 *  it under the terms of the GNU General Public License as published by
14
 *  the Free Software Foundation; either version 3 of the License, or
15
 *  (at your option) any later version.
16
 *
17
 *  The GNU General Public License can be found at
18
 *  http://www.gnu.org/copyleft/gpl.html.
19
 *
20
 *  This script is distributed in the hope that it will be useful,
21
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 *  GNU General Public License for more details.
24
 *
25
 *  This copyright notice MUST APPEAR in all copies of the script!
26
 ***************************************************************/
27
28
use ApacheSolrForTypo3\Solr\ConnectionManager;
29
use ApacheSolrForTypo3\Solr\Domain\Search\Query\QueryBuilder;
30
use ApacheSolrForTypo3\Solr\Domain\Search\Query\SuggestQuery;
31
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Result\SearchResult;
32
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Result\SearchResultCollection;
33
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\SearchResultSet;
34
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\SearchResultSetService;
35
use ApacheSolrForTypo3\Solr\Domain\Search\SearchRequest;
36
use ApacheSolrForTypo3\Solr\Search;
37
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
39
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
40
41
/**
42
 * Class SuggestService
43
 *
44
 * @author Frans Saris <[email protected]>
45
 * @author Timo Hund <[email protected]>
46
 * @package ApacheSolrForTypo3\Solr\Domain\Search\Suggest
47
 */
48
class SuggestService {
49
50
    /**
51
     * @var TypoScriptFrontendController
52
     */
53
    protected $tsfe;
54
55
    /**
56
     * @var SearchResultSetService
57
     */
58
    protected $searchService;
59
60
    /**
61
     * @var TypoScriptConfiguration
62
     */
63
    protected $typoScriptConfiguration;
64
65
    /**
66
     * @var QueryBuilder
67
     */
68
    protected $queryBuilder;
69
70
    /**
71
     * SuggestService constructor.
72
     * @param TypoScriptFrontendController $tsfe
73
     * @param SearchResultSetService $searchResultSetService
74
     * @param QueryBuilder|null $queryBuilder
75
     */
76 3
    public function __construct(TypoScriptFrontendController $tsfe, SearchResultSetService $searchResultSetService, TypoScriptConfiguration $typoScriptConfiguration, QueryBuilder $queryBuilder = null)
77
    {
78 3
        $this->tsfe = $tsfe;
79 3
        $this->searchService = $searchResultSetService;
80 3
        $this->typoScriptConfiguration = $typoScriptConfiguration;
81 3
        $this->queryBuilder = $queryBuilder ?? GeneralUtility::makeInstance(QueryBuilder::class, /** @scrutinizer ignore-type */ $typoScriptConfiguration);
82 3
    }
83
84
    /**
85
     * Build an array structure of the suggestions.
86
     *
87
     * @param SearchRequest $searchRequest
88
     * @param array $additionalFilters
89
     * @return array
90
     */
91 3
    public function getSuggestions(SearchRequest $searchRequest, array $additionalFilters = []) : array
92
    {
93 3
        $requestId = (int)$this->tsfe->getRequestedId();
94 3
        $groupList = (string)$this->tsfe->gr_list;
95
96 3
        $suggestQuery = $this->queryBuilder->buildSuggestQuery($searchRequest->getRawUserQuery(), $additionalFilters, $requestId, $groupList);
97 3
        $solrSuggestions = $this->getSolrSuggestions($suggestQuery);
98
99 3
        if ($solrSuggestions === []) {
100 1
            return ['status' => false];
101
        }
102
103 2
        $maxSuggestions = $this->typoScriptConfiguration->getSuggestNumberOfSuggestions();
104 2
        $showTopResults = $this->typoScriptConfiguration->getSuggestShowTopResults();
105 2
        $suggestions    = $this->getSuggestionArray($suggestQuery, $solrSuggestions, $maxSuggestions);
106
107 2
        if (!$showTopResults) {
108 1
            return $this->getResultArray($searchRequest, $suggestions, [], false);
109
        }
110
111 1
        return $this->addTopResultsToSuggestions($searchRequest, $suggestions, $additionalFilters);
112
    }
113
114
    /**
115
     * Determines the top results and adds them to the suggestions.
116
     *
117
     * @param SearchRequest $searchRequest
118
     * @param array $suggestions
119
     * @param array $additionalFilters
120
     * @return array
121
     */
122 1
    protected function addTopResultsToSuggestions(SearchRequest $searchRequest, $suggestions, array $additionalFilters) : array
123
    {
124 1
        $maxDocuments = $this->typoScriptConfiguration->getSuggestNumberOfTopResults();
125
126
        // perform the current search.
127 1
        $searchRequest->setResultsPerPage($maxDocuments);
128 1
        $searchRequest->setAdditionalFilters($additionalFilters);
129
130 1
        $didASecondSearch = false;
131 1
        $documents = [];
132
133 1
        $searchResultSet = $this->doASearch($searchRequest);
134 1
        $results = $searchResultSet->getSearchResults();
135 1
        if (count($results) > 0) {
136 1
            $documents = $this->addDocumentsWhenLimitNotReached($documents, $results, $maxDocuments);
137
        }
138
139 1
        $suggestionKeys = array_keys($suggestions);
140 1
        $bestSuggestion = reset($suggestionKeys);
141 1
        $bestSuggestionRequest = $searchRequest->getCopyForSubRequest();
142 1
        $bestSuggestionRequest->setRawQueryString($bestSuggestion);
143 1
        $bestSuggestionRequest->setResultsPerPage($maxDocuments);
144 1
        $bestSuggestionRequest->setAdditionalFilters($additionalFilters);
145
146
        // No results found, use first proposed suggestion to perform the search
147 1
        if (count($documents) === 0 && !empty($suggestions) && ($searchResultSet = $this->doASearch($bestSuggestionRequest)) && count($searchResultSet->getSearchResults()) > 0) {
148
            $didASecondSearch = true;
149
            $documentsToAdd = $searchResultSet->getSearchResults();
150
            $documents = $this->addDocumentsWhenLimitNotReached($documents, $documentsToAdd, $maxDocuments);
151
        }
152
153 1
        return $this->getResultArray($searchRequest, $suggestions, $documents, $didASecondSearch);
154
    }
155
156
    /**
157
     * Retrieves the suggestions from the solr server.
158
     *
159
     * @param SuggestQuery $suggestQuery
160
     * @return array
161
     */
162
    protected function getSolrSuggestions(SuggestQuery $suggestQuery) : array
163
    {
164
        $pageId = $this->tsfe->getRequestedId();
165
        $languageId = $this->tsfe->sys_language_uid;
166
        $solr = GeneralUtility::makeInstance(ConnectionManager::class)->getConnectionByPageId($pageId, $languageId);
167
        $search = GeneralUtility::makeInstance(Search::class, /** @scrutinizer ignore-type */ $solr);
168
        $response = $search->search($suggestQuery, 0, 0);
169
170
        $rawResponse = $response->getRawResponse();
171
        $results = json_decode($rawResponse);
172
        $suggestConfig = $this->typoScriptConfiguration->getObjectByPath('plugin.tx_solr.suggest.');
173
        $facetSuggestions = $results->facet_counts->facet_fields->{$suggestConfig['suggestField']};
174
        $facetSuggestions = get_object_vars($facetSuggestions);
175
176
        return $facetSuggestions ?? [];
177
    }
178
179
    /**
180
     * Extracts the suggestions from solr as array.
181
     *
182
     * @param SuggestQuery $suggestQuery
183
     * @param array $solrSuggestions
184
     * @param integer $maxSuggestions
185
     * @return array
186
     */
187 2
    protected function getSuggestionArray(SuggestQuery $suggestQuery, $solrSuggestions, $maxSuggestions) : array
188
    {
189 2
        $queryString = $suggestQuery->getQueryStringContainer()->getKeywords();
190 2
        $suggestionCount = 0;
191 2
        $suggestions = [];
192 2
        foreach ($solrSuggestions as $string => $count) {
193 2
            $suggestion = trim($queryString . ' ' . $string);
194 2
            $suggestions[$suggestion] = $count;
195 2
            $suggestionCount++;
196 2
            if ($suggestionCount === $maxSuggestions) {
197 2
                return $suggestions;
198
            }
199
        }
200
201 2
        return $suggestions;
202
    }
203
204
    /**
205
     * Adds documents from a collection to the result collection as soon as the limit is not reached.
206
     *
207
     * @param array $documents
208
     * @param SearchResultCollection $documentsToAdd
209
     * @param integer $maxDocuments
210
     * @return array
211
     */
212 1
    protected function addDocumentsWhenLimitNotReached(array $documents, SearchResultCollection $documentsToAdd, int $maxDocuments)  : array
213
    {
214
        /** @var SearchResult $document */
215 1
        foreach ($documentsToAdd as $document) {
216 1
            $documents[] = $this->getDocumentAsArray($document);
217 1
            if (count($documents) >= $maxDocuments) {
218 1
                return $documents;
219
            }
220
        }
221
222
        return $documents;
223
    }
224
225
    /**
226
     * Creates an array representation of the result and returns it.
227
     *
228
     * @param SearchResult $document
229
     * @return array
230
     */
231 1
    protected function getDocumentAsArray(SearchResult $document) : array
232
    {
233
        return [
234 1
            'link' => $document->getUrl(),
235 1
            'type' => $document->getField('type_stringS') ? $document->getField('type_stringS')['value'] : $document->getType(),
236 1
            'title' => $document->getTitle(),
237 1
            'content' => $document->getContent(),
238 1
            'group' => $document->getHasGroupItem() ? $document->getGroupItem()->getGroupValue() : '',
239 1
            'previewImage' => $document->getField('previewImage_stringS') ? $document->getField('previewImage_stringS')['value'] : '',
240
        ];
241
    }
242
243
    /**
244
     * Runs a search and returns the results.
245
     *
246
     * @param SearchRequest $searchRequest
247
     * @return \ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\SearchResultSet
248
     */
249 1
    protected function doASearch($searchRequest) : SearchResultSet
250
    {
251 1
        return $this->searchService->search($searchRequest);
252
    }
253
254
    /**
255
     * Creates an result array with the required fields.
256
     *
257
     * @param SearchRequest $searchRequest
258
     * @param array $suggestions
259
     * @param array $documents
260
     * @param boolean $didASecondSearch
261
     * @return array
262
     */
263 2
    protected function getResultArray(SearchRequest $searchRequest, $suggestions, $documents, $didASecondSearch) : array
264
    {
265 2
        return ['suggestions' => $suggestions, 'suggestion' => $searchRequest->getRawUserQuery(), 'documents' => $documents, 'didSecondSearch' => $didASecondSearch];
266
    }
267
268
269
}