Passed
Push — bufferfix ( 590e87...51cc6c )
by Simon
09:20 queued 07:07
created

BaseIndex   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 378
Duplicated Lines 0 %

Test Coverage

Coverage 95.9%

Importance

Changes 12
Bugs 1 Features 0
Metric Value
eloc 126
c 12
b 1
f 0
dl 0
loc 378
ccs 117
cts 122
cp 0.959
rs 9.92
wmc 31

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 2
A init() 0 14 4
A initFromConfig() 0 16 4
A getConfig() 0 7 2
A getFieldsForIndexing() 0 23 2
A getQueryTerms() 0 3 1
A buildSolrQuery() 0 12 1
A doRetry() 0 6 5
A buildFactory() 0 12 1
A spellcheckRetry() 0 11 1
A getSynonyms() 0 6 1
A getQueryFactory() 0 3 1
A uploadConfig() 0 26 3
A doSearch() 0 33 3
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Indexes;
5
6
use Exception;
7
use Firesphere\SolrSearch\Factories\QueryComponentFactory;
8
use Firesphere\SolrSearch\Helpers\SolrLogger;
9
use Firesphere\SolrSearch\Helpers\Synonyms;
10
use Firesphere\SolrSearch\Interfaces\ConfigStore;
11
use Firesphere\SolrSearch\Queries\BaseQuery;
12
use Firesphere\SolrSearch\Results\SearchResult;
13
use Firesphere\SolrSearch\Services\SchemaService;
14
use Firesphere\SolrSearch\Services\SolrCoreService;
15
use Firesphere\SolrSearch\States\SiteState;
16
use Firesphere\SolrSearch\Traits\BaseIndexTrait;
17
use Firesphere\SolrSearch\Traits\GetterSetterTrait;
18
use GuzzleHttp\Exception\GuzzleException;
19
use LogicException;
20
use SilverStripe\Control\Controller;
21
use SilverStripe\Control\Director;
22
use SilverStripe\Core\Config\Config;
23
use SilverStripe\Core\Config\Configurable;
24
use SilverStripe\Core\Extensible;
25
use SilverStripe\Core\Injector\Injectable;
26
use SilverStripe\Core\Injector\Injector;
27
use SilverStripe\Dev\Deprecation;
28
use SilverStripe\ORM\ValidationException;
29
use SilverStripe\SiteConfig\SiteConfig;
30
use SilverStripe\View\ArrayData;
31
use Solarium\Core\Client\Adapter\Guzzle;
32
use Solarium\Core\Client\Client;
33
use Solarium\QueryType\Select\Query\Query;
34
use Solarium\QueryType\Select\Result\Result;
35
36
/**
37
 * Base for creating a new Solr core.
38
 *
39
 * Base index settings and methods. Should be extended with at least a name for the index.
40
 * This is an abstract class that can not be instantiated on it's own
41
 *
42
 * @package Firesphere\SolrSearch\Indexes
43
 */
44
abstract class BaseIndex
45
{
46
    use Extensible;
47
    use Configurable;
48
    use Injectable;
49
    use GetterSetterTrait;
50
    use BaseIndexTrait;
51
    /**
52
     * Session key for the query history
53
     */
54
    const SEARCH_HISTORY_KEY = 'query_history';
55
56
    /**
57
     * Field types that can be added
58
     * Used in init to call build methods from configuration yml
59
     *
60
     * @array
61
     */
62
    private static $fieldTypes = [
63
        'FulltextFields',
64
        'SortFields',
65
        'FilterFields',
66
        'BoostedFields',
67
        'CopyFields',
68
        'DefaultField',
69
        'FacetFields',
70
        'StoredFields',
71
    ];
72
    /**
73
     * The raw query result
74
     *
75
     * @var Result
76
     */
77
    protected $rawQuery;
78
    /**
79
     * {@link SchemaService}
80
     *
81
     * @var SchemaService
82
     */
83
    protected $schemaService;
84
    /**
85
     * {@link QueryComponentFactory}
86
     *
87
     * @var QueryComponentFactory
88
     */
89
    protected $queryFactory;
90
    /**
91
     * The query terms as an array
92
     *
93
     * @var array
94
     */
95
    protected $queryTerms = [];
96
    /**
97
     * Should a retry occur if nothing was found and there are suggestions to follow
98
     *
99
     * @var bool
100
     */
101
    private $retry = false;
102
103
    /**
104
     * BaseIndex constructor.
105
     */
106 72
    public function __construct()
107
    {
108
        // Set up the client
109 72
        $config = Config::inst()->get(SolrCoreService::class, 'config');
110 72
        $config['endpoint'] = $this->getConfig($config['endpoint']);
111 72
        $this->client = new Client($config);
112 72
        $this->client->setAdapter(new Guzzle());
113 72
        $session = Controller::curr()->getRequest()->getSession();
114 72
        $this->history = $session->get(self::SEARCH_HISTORY_KEY) ?: [];
115
116
        // Set up the schema service, only used in the generation of the schema
117 72
        $schemaService = Injector::inst()->get(SchemaService::class, false);
118 72
        $schemaService->setIndex($this);
119 72
        $schemaService->setStore(Director::isDev());
120 72
        $this->schemaService = $schemaService;
121 72
        $this->queryFactory = Injector::inst()->get(QueryComponentFactory::class, false);
122
123 72
        $this->extend('onBeforeInit');
124 72
        $this->init();
125 72
        $this->extend('onAfterInit');
126 72
    }
127
128
    /**
129
     * Build a full config for all given endpoints
130
     * This is to add the current index to e.g. an index or select
131
     *
132
     * @param array $endpoints
133
     * @return array
134
     */
135 72
    public function getConfig($endpoints): array
136
    {
137 72
        foreach ($endpoints as $host => $endpoint) {
138 72
            $endpoints[$host]['core'] = $this->getIndexName();
139
        }
140
141 72
        return $endpoints;
142
    }
143
144
    /**
145
     * Name of this index.
146
     *
147
     * @return string
148
     */
149
    abstract public function getIndexName();
150
151
    /**
152
     * Required to initialise the fields.
153
     * It's loaded in to the non-static properties for backward compatibility with FTS
154
     * Also, it's a tad easier to use this way, loading the other way around would be very
155
     * memory intensive, as updating the config for each item is not efficient
156
     */
157 71
    public function init()
158
    {
159 71
        if (!self::config()->get($this->getIndexName())) {
160 71
            Deprecation::notice('5', 'Please set an index name and use a config yml');
161
162 71
            return;
163
        }
164
165 71
        if (!empty($this->getClasses()) && !$this->usedAllFields) {
166
            Deprecation::notice('5', 'It is adviced to use a config YML for most cases');
167
        }
168
169
170 71
        $this->initFromConfig();
171 71
    }
172
173
    /**
174
     * Generate the config from yml if possible
175
     */
176 71
    protected function initFromConfig(): void
177
    {
178 71
        $config = self::config()->get($this->getIndexName());
179
180 71
        if (!array_key_exists('Classes', $config)) {
181
            throw new LogicException('No classes to index found!');
182
        }
183
184 71
        $this->setClasses($config['Classes']);
185
186
        // For backward compatibility, copy the config to the protected values
187
        // Saves doubling up further down the line
188 71
        foreach (self::$fieldTypes as $type) {
189 71
            if (array_key_exists($type, $config)) {
190 71
                $method = 'set' . $type;
191 71
                $this->$method($config[$type]);
192
            }
193
        }
194 71
    }
195
196
    /**
197
     * Default returns a SearchResult. It can return an ArrayData if FTS Compat is enabled
198
     *
199
     * @param BaseQuery $query
200
     * @return SearchResult|ArrayData|mixed
201
     * @throws GuzzleException
202
     * @throws ValidationException
203
     * @throws \ReflectionException
204
     */
205 5
    public function doSearch(BaseQuery $query)
206
    {
207 5
        SiteState::alterQuery($query);
208
        // Build the actual query parameters
209 5
        $clientQuery = $this->buildSolrQuery($query);
210
211 5
        $this->extend('onBeforeSearch', $query, $clientQuery);
212
213
        try {
214 5
            $result = $this->client->select($clientQuery);
215
        } catch (Exception $e) {
216
            $logger = new SolrLogger();
217
            $logger->saveSolrLog('Query');
218
        }
219
220 5
        $this->rawQuery = $result;
221
222
        // Handle the after search first. This gets a raw search result
223 5
        $this->extend('onAfterSearch', $result);
224 5
        $searchResult = new SearchResult($result, $query, $this);
225 5
        if ($this->doRetry($query, $result, $searchResult)) {
226 1
            return $this->spellcheckRetry($query, $searchResult);
227
        }
228
229
        // And then handle the search results, which is a useable object for SilverStripe
230 5
        $this->extend('updateSearchResults', $searchResult);
231
232 5
        Controller::curr()
233 5
            ->getRequest()
234 5
            ->getSession()
235 5
            ->set(self::SEARCH_HISTORY_KEY, $this->getHistory());
236
237 5
        return $searchResult;
238
    }
239
240
    /**
241
     * From the given BaseQuery, generate a Solarium ClientQuery object
242
     *
243
     * @param BaseQuery $query
244
     * @return Query
245
     */
246 5
    public function buildSolrQuery(BaseQuery $query): Query
247
    {
248 5
        $clientQuery = $this->client->createSelect();
249 5
        $factory = $this->buildFactory($query, $clientQuery);
250
251 5
        $clientQuery = $factory->buildQuery();
252 5
        $this->queryTerms = $factory->getQueryArray();
253
254 5
        $queryData = implode(' ', $this->queryTerms);
255 5
        $clientQuery->setQuery($queryData);
256
257 5
        return $clientQuery;
258
    }
259
260
    /**
261
     * Build a factory to use in the SolrQuery building. {@link static::buildSolrQuery()}
262
     *
263
     * @param BaseQuery $query
264
     * @param Query $clientQuery
265
     * @return QueryComponentFactory|mixed
266
     */
267 5
    protected function buildFactory(BaseQuery $query, Query $clientQuery)
268
    {
269 5
        $factory = $this->queryFactory;
270
271 5
        $helper = $clientQuery->getHelper();
272
273 5
        $factory->setQuery($query);
274 5
        $factory->setClientQuery($clientQuery);
275 5
        $factory->setHelper($helper);
276 5
        $factory->setIndex($this);
277
278 5
        return $factory;
279
    }
280
281
    /**
282
     * Check if the query should be retried with spellchecking
283
     * Conditions are:
284
     * It is not already a retry with spellchecking
285
     * Spellchecking is enabled
286
     * If spellchecking is enabled and nothing is found OR it should follow spellchecking none the less
287
     * There is a spellcheck output
288
     *
289
     * @param BaseQuery $query
290
     * @param Result $result
291
     * @param SearchResult $searchResult
292
     * @return bool
293
     */
294 5
    protected function doRetry(BaseQuery $query, Result $result, SearchResult $searchResult): bool
295
    {
296 5
        return !$this->retry &&
297 5
            $query->hasSpellcheck() &&
298 5
            ($query->shouldFollowSpellcheck() || $result->getNumFound() === 0) &&
299 5
            $searchResult->getCollatedSpellcheck();
300
    }
301
302
    /**
303
     * Retry the query with the first collated spellcheck found.
304
     *
305
     * @param BaseQuery $query
306
     * @param SearchResult $searchResult
307
     * @return SearchResult|mixed|ArrayData
308
     * @throws GuzzleException
309
     * @throws ValidationException
310
     * @throws \ReflectionException
311
     */
312 1
    protected function spellcheckRetry(BaseQuery $query, SearchResult $searchResult)
313
    {
314 1
        $terms = $query->getTerms();
315 1
        $spellChecked = $searchResult->getCollatedSpellcheck();
316
        // Remove the fuzzyness from the collated check
317 1
        $term = preg_replace('/~\d+/', '', $spellChecked);
318 1
        $terms[0]['text'] = $term;
319 1
        $query->setTerms($terms);
320 1
        $this->retry = true;
321
322 1
        return $this->doSearch($query);
323
    }
324
325
    /**
326
     * Get all fields that are required for indexing in a unique way
327
     *
328
     * @return array
329
     */
330 8
    public function getFieldsForIndexing(): array
331
    {
332 8
        $facets = [];
333 8
        foreach ($this->getFacetFields() as $field) {
334 7
            $facets[] = $field['Field'];
335
        }
336
        // Return values to make the key reset
337
        // Only return unique values
338
        // And make it all a single array
339 8
        $fields = array_values(
340 8
            array_unique(
341 8
                array_merge(
342 8
                    $this->getFulltextFields(),
343 8
                    $this->getSortFields(),
344 8
                    $facets,
345 8
                    $this->getFilterFields()
346
                )
347
            )
348
        );
349
350 8
        $this->extend('updateFieldsForIndexing', $fields);
351
352 8
        return $fields;
353
    }
354
355
    /**
356
     * Upload config for this index to the given store
357
     *
358
     * @param ConfigStore $store
359
     */
360 32
    public function uploadConfig(ConfigStore $store): void
361
    {
362
        // @todo use types/schema/elevate rendering
363
        // Upload the config files for this index
364
        // Create a default schema which we can manage later
365 32
        $schema = (string)$this->schemaService->generateSchema();
366 32
        $store->uploadString(
367 32
            $this->getIndexName(),
368 32
            'schema.xml',
369 32
            $schema
370
        );
371
372
373 32
        $synonyms = $this->getSynonyms();
374
375
        // Upload synonyms
376 32
        $store->uploadString(
377 32
            $this->getIndexName(),
378 32
            'synonyms.txt',
379 32
            $synonyms
380
        );
381
382
        // Upload additional files
383 32
        foreach (glob($this->schemaService->getExtrasPath() . '/*') as $file) {
384 32
            if (is_file($file)) {
385 32
                $store->uploadFile($this->getIndexName(), $file);
386
            }
387
        }
388 32
    }
389
390
    /**
391
     * Add synonyms. Public to be extendable
392
     *
393
     * @param bool $defaults Include UK to US synonyms
394
     * @return string
395
     */
396 32
    public function getSynonyms($defaults = true): string
397
    {
398 32
        $synonyms = Synonyms::getSynonymsAsString($defaults);
399 32
        $siteConfigSynonyms = SiteConfig::current_site_config()->getField('SearchSynonyms');
400
401 32
        return sprintf('%s%s', $synonyms, $siteConfigSynonyms);
402
    }
403
404
    /**
405
     * Get the final, generated terms
406
     *
407
     * @return array
408
     */
409 2
    public function getQueryTerms(): array
410
    {
411 2
        return $this->queryTerms;
412
    }
413
414
    /**
415
     * Get the QueryComponentFactory. {@link QueryComponentFactory}
416
     *
417
     * @return QueryComponentFactory
418
     */
419 1
    public function getQueryFactory(): QueryComponentFactory
420
    {
421 1
        return $this->queryFactory;
422
    }
423
}
424