Passed
Push — hans/authentication ( f88d5d...b8d786 )
by Simon
05:24
created

BaseIndex::doSearch()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.004

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 3
eloc 16
c 5
b 0
f 0
nc 3
nop 1
dl 0
loc 31
ccs 12
cts 13
cp 0.9231
crap 3.004
rs 9.7333
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
use Symfony\Component\EventDispatcher\EventDispatcher;
43
44
/**
45
 * Base for creating a new Solr core.
46
 *
47
 * Base index settings and methods. Should be extended with at least a name for the index.
48
 * This is an abstract class that can not be instantiated on it's own
49
 *
50
 * @package Firesphere\SolrSearch\Indexes
51
 */
52
abstract class BaseIndex
53
{
54
    use Extensible;
55
    use Configurable;
56
    use Injectable;
57
    use GetterSetterTrait;
58
    use BaseIndexTrait;
59
60
    /**
61
     * Field types that can be added
62
     * Used in init to call build methods from configuration yml
63
     *
64
     * @array
65
     */
66
    private static $fieldTypes = [
67
        'FulltextFields',
68
        'SortFields',
69
        'FilterFields',
70
        'BoostedFields',
71
        'CopyFields',
72
        'DefaultField',
73
        'FacetFields',
74
        'StoredFields',
75
    ];
76
    /**
77
     * {@link SchemaFactory}
78
     *
79
     * @var SchemaFactory Schema factory for generating the schema
80
     */
81
    protected $schemaFactory;
82
    /**
83
     * {@link QueryComponentFactory}
84
     *
85
     * @var QueryComponentFactory Generator for all components
86
     */
87
    protected $queryFactory;
88
    /**
89
     * @var array The query terms as an array
90
     */
91
    protected $queryTerms = [];
92
    /**
93
     * @var Query Query that will hit the client
94
     */
95
    protected $clientQuery;
96
    /**
97
     * @var bool Signify if a retry should occur if nothing was found and there are suggestions to follow
98
     */
99
    private $retry = false;
100
101
    /**
102
     * BaseIndex constructor.
103
     */
104 53
    public function __construct()
105
    {
106
        // Set up the client
107 53
        $config = Config::inst()->get(SolrCoreService::class, 'config');
108 53
        $config['endpoint'] = $this->getConfig($config['endpoint']);
109 53
        $adapter = new Guzzle();
0 ignored issues
show
Deprecated Code introduced by
The class Solarium\Core\Client\Adapter\Guzzle has been deprecated: Deprecated since Solarium 5.2 and will be removed in Solarium 6. Use Psr18Adapter instead. ( Ignorable by Annotation )

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

109
        $adapter = /** @scrutinizer ignore-deprecated */ new Guzzle();
Loading history...
110 53
        $dispatcher = new EventDispatcher();
111 53
        $this->client = new Client($adapter, $dispatcher, $config);
112
113
        // Set up the schema service, only used in the generation of the schema
114 53
        $schemaFactory = Injector::inst()->get(SchemaFactory::class, false);
115 53
        $schemaFactory->setIndex($this);
116 53
        $schemaFactory->setStore(Director::isDev());
117 53
        $this->schemaFactory = $schemaFactory;
118 53
        $this->queryFactory = Injector::inst()->get(QueryComponentFactory::class, false);
119
120 53
        $this->extend('onBeforeInit');
121 53
        $this->init();
122 53
        $this->extend('onAfterInit');
123 53
    }
124
125
    /**
126
     * Build a full config for all given endpoints
127
     * This is to add the current index to e.g. an index or select
128
     *
129
     * @param array $endpoints
130
     * @return array
131
     */
132 53
    public function getConfig($endpoints): array
133
    {
134 53
        foreach ($endpoints as $host => $endpoint) {
135 53
            $endpoints[$host]['core'] = $this->getIndexName();
136
        }
137
138 53
        return $endpoints;
139
    }
140
141
    /**
142
     * Name of this index.
143
     *
144
     * @return string
145
     */
146
    abstract public function getIndexName();
147
148
    /**
149
     * Required to initialise the fields.
150
     * It's loaded in to the non-static properties for backward compatibility with FTS
151
     * Also, it's a tad easier to use this way, loading the other way around would be very
152
     * memory intensive, as updating the config for each item is not efficient
153
     */
154 49
    public function init()
155
    {
156 49
        $config = self::config()->get($this->getIndexName());
157 49
        if (!$config) {
158 49
            Deprecation::notice('5', 'Please set an index name and use a config yml');
159
        }
160
161 49
        if (!empty($this->getClasses())) {
162 49
            if (!$this->usedAllFields) {
163 49
                Deprecation::notice('5', 'It is advised to use a config YML for most cases');
164
            }
165
166 49
            return;
167
        }
168
169 41
        $this->initFromConfig($config);
170 41
    }
171
172
    /**
173
     * Generate the config from yml if possible
174
     * @param array|null $config
175
     */
176 41
    protected function initFromConfig($config): void
177
    {
178 41
        if (!$config || !array_key_exists('Classes', $config)) {
179 2
            throw new LogicException('No classes or config to index found!');
180
        }
181
182 41
        $this->setClasses($config['Classes']);
183
184
        // For backward compatibility, copy the config to the protected values
185
        // Saves doubling up further down the line
186 41
        foreach (self::$fieldTypes as $type) {
187 41
            if (array_key_exists($type, $config)) {
188 41
                $method = 'set' . $type;
189 41
                $this->$method($config[$type]);
190
            }
191
        }
192 41
    }
193
194
    /**
195
     * Default returns a SearchResult. It can return an ArrayData if FTS Compat is enabled
196
     *
197
     * @param BaseQuery $query
198
     * @return SearchResult|ArrayData|mixed
199
     * @throws GuzzleException
200
     * @throws ValidationException
201
     * @throws ReflectionException
202
     * @throws Exception
203
     */
204 6
    public function doSearch(BaseQuery $query)
205
    {
206 6
        SiteState::alterQuery($query);
207
        // Build the actual query parameters
208 6
        $this->clientQuery = $this->buildSolrQuery($query);
209
        // Set the sorting
210 6
        $this->clientQuery->addSorts($query->getSort());
211
212 6
        $this->extend('onBeforeSearch', $query, $this->clientQuery);
213
214
        try {
215 6
            $result = $this->client->select($this->clientQuery);
216
        } catch (Exception $error) {
217
            // @codeCoverageIgnoreStart
218
            $logger = new SolrLogger();
219
            $logger->saveSolrLog('Query');
220
            throw $error;
221
            // @codeCoverageIgnoreEnd
222
        }
223
224
        // Handle the after search first. This gets a raw search result
225 6
        $this->extend('onAfterSearch', $result);
226 6
        $searchResult = new SearchResult($result, $query, $this);
227 6
        if ($this->doRetry($query, $result, $searchResult)) {
228 2
            return $this->spellcheckRetry($query, $searchResult);
229
        }
230
231
        // And then handle the search results, which is a useable object for SilverStripe
232 6
        $this->extend('updateSearchResults', $searchResult);
233
234 6
        return $searchResult;
235
    }
236
237
    /**
238
     * From the given BaseQuery, generate a Solarium ClientQuery object
239
     *
240
     * @param BaseQuery $query
241
     * @return Query
242
     */
243 6
    public function buildSolrQuery(BaseQuery $query): Query
244
    {
245 6
        $clientQuery = $this->client->createSelect();
246 6
        $factory = $this->buildFactory($query, $clientQuery);
247
248 6
        $clientQuery = $factory->buildQuery();
249 6
        $this->queryTerms = $factory->getQueryArray();
250
251 6
        $queryData = implode(' ', $this->queryTerms);
252 6
        $clientQuery->setQuery($queryData);
253
254 6
        return $clientQuery;
255
    }
256
257
    /**
258
     * Build a factory to use in the SolrQuery building. {@link static::buildSolrQuery()}
259
     *
260
     * @param BaseQuery $query
261
     * @param Query $clientQuery
262
     * @return QueryComponentFactory|mixed
263
     */
264 6
    protected function buildFactory(BaseQuery $query, Query $clientQuery)
265
    {
266 6
        $factory = $this->queryFactory;
267
268 6
        $helper = $clientQuery->getHelper();
269
270 6
        $factory->setQuery($query);
271 6
        $factory->setClientQuery($clientQuery);
272 6
        $factory->setHelper($helper);
273 6
        $factory->setIndex($this);
274
275 6
        return $factory;
276
    }
277
278
    /**
279
     * Check if the query should be retried with spellchecking
280
     * Conditions are:
281
     * It is not already a retry with spellchecking
282
     * Spellchecking is enabled
283
     * If spellchecking is enabled and nothing is found OR it should follow spellchecking none the less
284
     * There is a spellcheck output
285
     *
286
     * @param BaseQuery $query
287
     * @param Result $result
288
     * @param SearchResult $searchResult
289
     * @return bool
290
     */
291 6
    protected function doRetry(BaseQuery $query, Result $result, SearchResult $searchResult): bool
292
    {
293 6
        return !$this->retry &&
294 6
            $query->hasSpellcheck() &&
295 6
            ($query->shouldFollowSpellcheck() || $result->getNumFound() === 0) &&
296 6
            $searchResult->getCollatedSpellcheck();
297
    }
298
299
    /**
300
     * Retry the query with the first collated spellcheck found.
301
     *
302
     * @param BaseQuery $query
303
     * @param SearchResult $searchResult
304
     * @return SearchResult|mixed|ArrayData
305
     * @throws GuzzleException
306
     * @throws ValidationException
307
     * @throws ReflectionException
308
     */
309 2
    protected function spellcheckRetry(BaseQuery $query, SearchResult $searchResult)
310
    {
311 2
        $terms = $query->getTerms();
312 2
        $spellChecked = $searchResult->getCollatedSpellcheck();
313
        // Remove the fuzzyness from the collated check
314 2
        $term = preg_replace('/~\d+/', '', $spellChecked);
315 2
        $terms[0]['text'] = $term;
316 2
        $query->setTerms($terms);
317 2
        $this->retry = true;
318
319 2
        return $this->doSearch($query);
320
    }
321
322
    /**
323
     * Get all fields that are required for indexing in a unique way
324
     *
325
     * @return array
326
     */
327 10
    public function getFieldsForIndexing(): array
328
    {
329 10
        $facets = [];
330 10
        foreach ($this->getFacetFields() as $field) {
331 9
            $facets[] = $field['Field'];
332
        }
333
        // Return values to make the key reset
334
        // Only return unique values
335
        // And make it all a single array
336 10
        $fields = array_values(
337 10
            array_unique(
338 10
                array_merge(
339 10
                    $this->getFulltextFields(),
340 10
                    $this->getSortFields(),
341 10
                    $facets,
342 10
                    $this->getFilterFields()
343
                )
344
            )
345
        );
346
347 10
        $this->extend('updateFieldsForIndexing', $fields);
348
349 10
        return $fields;
350
    }
351
352
    /**
353
     * Upload config for this index to the given store
354
     *
355
     * @param ConfigStore $store
356
     */
357 35
    public function uploadConfig(ConfigStore $store): void
358
    {
359
        // @todo use types/schema/elevate rendering
360
        // Upload the config files for this index
361
        // Create a default schema which we can manage later
362 35
        $schema = (string)$this->schemaFactory->generateSchema();
363 35
        $store->uploadString(
364 35
            $this->getIndexName(),
365 35
            'schema.xml',
366 35
            $schema
367
        );
368
369 35
        $this->getSynonyms($store);
370
371
        // Upload additional files
372 35
        foreach (glob($this->schemaFactory->getExtrasPath() . '/*') as $file) {
373 35
            if (is_file($file)) {
374 35
                $store->uploadFile($this->getIndexName(), $file);
375
            }
376
        }
377 35
    }
378
379
    /**
380
     * Add synonyms. Public to be extendable
381
     *
382
     * @param ConfigStore $store Store to use to write synonyms
383
     * @param bool $defaults Include UK to US synonyms
384
     * @return string
385
     */
386 35
    public function getSynonyms($store = null, $defaults = true)
387
    {
388 35
        $synonyms = Synonyms::getSynonymsAsString($defaults);
389
        /** @var DataList|SearchSynonym[] $syn */
390 35
        $syn = SearchSynonym::get();
391 35
        foreach ($syn as $synonym) {
392 1
            $synonyms .= $synonym->getCombinedSynonym();
393
        }
394
395
        // Upload synonyms
396 35
        if ($store) {
397 35
            $store->uploadString(
398 35
                $this->getIndexName(),
399 35
                'synonyms.txt',
400 35
                $synonyms
401
            );
402
        }
403
404 35
        return $synonyms;
405
    }
406
407
    /**
408
     * Get the final, generated terms
409
     *
410
     * @return array
411
     */
412 2
    public function getQueryTerms(): array
413
    {
414 2
        return $this->queryTerms;
415
    }
416
417
    /**
418
     * Get the QueryComponentFactory. {@link QueryComponentFactory}
419
     *
420
     * @return QueryComponentFactory
421
     */
422 1
    public function getQueryFactory(): QueryComponentFactory
423
    {
424 1
        return $this->queryFactory;
425
    }
426
427
    /**
428
     * Retrieve the Solarium client Query object for this index operation
429
     *
430
     * @return Query
431
     */
432 1
    public function getClientQuery(): Query
433
    {
434 1
        return $this->clientQuery;
435
    }
436
}
437