Passed
Push — hans/searchfixes ( df80b9...49661c )
by Simon
06:22 queued 03:51
created

BaseIndex   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 380
Duplicated Lines 0 %

Test Coverage

Coverage 99.17%

Importance

Changes 12
Bugs 1 Features 0
Metric Value
eloc 125
c 12
b 1
f 0
dl 0
loc 380
ccs 119
cts 120
cp 0.9917
rs 9.68
wmc 34

15 Methods

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