Passed
Pull Request — master (#211)
by Simon
09:32 queued 03:02
created

BaseIndex::getClientQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
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 51
100
    /**
101
     * BaseIndex constructor.
102 51
     */
103 51
    public function __construct()
104 51
    {
105 51
        // Set up the client
106
        $config = Config::inst()->get(SolrCoreService::class, 'config');
107
        $config['endpoint'] = $this->getConfig($config['endpoint']);
108 51
        $this->client = new Client($config);
109 51
        $this->client->setAdapter(new Guzzle());
110 51
111 51
        // Set up the schema service, only used in the generation of the schema
112 51
        $schemaFactory = Injector::inst()->get(SchemaFactory::class, false);
113
        $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 51
118
        $this->extend('onBeforeInit');
119
        $this->init();
120
        $this->extend('onAfterInit');
121
    }
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 51
     *
127
     * @param array $endpoints
128 51
     * @return array
129 51
     */
130
    public function getConfig($endpoints): array
131
    {
132 51
        foreach ($endpoints as $host => $endpoint) {
133
            $endpoints[$host]['core'] = $this->getIndexName();
134
        }
135
136
        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 47
     * 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 47
     * memory intensive, as updating the config for each item is not efficient
151 47
     */
152 47
    public function init()
153
    {
154
        $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 47
        }
158
159
        if (!empty($this->getClasses())) {
160 47
            if (!$this->usedAllFields) {
161
                Deprecation::notice('5', 'It is advised to use a config YML for most cases');
162
            }
163 39
164 39
            return;
165
        }
166
167
        $this->initFromConfig($config);
168
    }
169
170 39
    /**
171
     * Generate the config from yml if possible
172 39
     * @param array|null $config
173 2
     */
174
    protected function initFromConfig($config): void
175
    {
176 39
        if (!$config || !array_key_exists('Classes', $config)) {
177
            throw new LogicException('No classes or config to index found!');
178
        }
179
180 39
        $this->setClasses($config['Classes']);
181 39
182 39
        // For backward compatibility, copy the config to the protected values
183 39
        // Saves doubling up further down the line
184
        foreach (self::$fieldTypes as $type) {
185
            if (array_key_exists($type, $config)) {
186 39
                $method = 'set' . $type;
187
                $this->$method($config[$type]);
188
            }
189
        }
190
    }
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 6
     * @throws ValidationException
199
     * @throws ReflectionException
200 6
     * @throws Exception
201
     */
202 6
    public function doSearch(BaseQuery $query)
203
    {
204 6
        SiteState::alterQuery($query);
205
        // Build the actual query parameters
206
        $this->clientQuery = $this->buildSolrQuery($query);
207 6
        // Set the sorting
208
        $this->clientQuery->addSorts($query->getSort());
209
210
        $this->extend('onBeforeSearch', $query, $this->clientQuery);
211
212
        try {
213
            $result = $this->client->select($this->clientQuery);
214
        } catch (Exception $error) {
215
            // @codeCoverageIgnoreStart
216
            $logger = new SolrLogger();
217 6
            $logger->saveSolrLog('Query');
218 6
            throw $error;
219 6
            // @codeCoverageIgnoreEnd
220 2
        }
221
222
        // Handle the after search first. This gets a raw search result
223
        $this->extend('onAfterSearch', $result);
224 6
        $searchResult = new SearchResult($result, $query, $this);
225
        if ($this->doRetry($query, $result, $searchResult)) {
226 6
            return $this->spellcheckRetry($query, $searchResult);
227
        }
228
229
        // And then handle the search results, which is a useable object for SilverStripe
230
        $this->extend('updateSearchResults', $searchResult);
231
232
        return $searchResult;
233
    }
234
235 6
    /**
236
     * From the given BaseQuery, generate a Solarium ClientQuery object
237 6
     *
238 6
     * @param BaseQuery $query
239
     * @return Query
240 6
     */
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
        $this->queryTerms = $factory->getQueryArray();
248
249
        $queryData = implode(' ', $this->queryTerms);
250
        $clientQuery->setQuery($queryData);
251
252
        return $clientQuery;
253
    }
254
255
    /**
256 6
     * Build a factory to use in the SolrQuery building. {@link static::buildSolrQuery()}
257
     *
258 6
     * @param BaseQuery $query
259
     * @param Query $clientQuery
260 6
     * @return QueryComponentFactory|mixed
261
     */
262 6
    protected function buildFactory(BaseQuery $query, Query $clientQuery)
263 6
    {
264 6
        $factory = $this->queryFactory;
265 6
266
        $helper = $clientQuery->getHelper();
267 6
268
        $factory->setQuery($query);
269
        $factory->setClientQuery($clientQuery);
270
        $factory->setHelper($helper);
271
        $factory->setIndex($this);
272
273
        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 6
     *
284
     * @param BaseQuery $query
285 6
     * @param Result $result
286 6
     * @param SearchResult $searchResult
287 6
     * @return bool
288 6
     */
289
    protected function doRetry(BaseQuery $query, Result $result, SearchResult $searchResult): bool
290
    {
291
        return !$this->retry &&
292
            $query->hasSpellcheck() &&
293
            ($query->shouldFollowSpellcheck() || $result->getNumFound() === 0) &&
294
            $searchResult->getCollatedSpellcheck();
295
    }
296
297
    /**
298
     * Retry the query with the first collated spellcheck found.
299
     *
300
     * @param BaseQuery $query
301 2
     * @param SearchResult $searchResult
302
     * @return SearchResult|mixed|ArrayData
303 2
     * @throws GuzzleException
304 2
     * @throws ValidationException
305
     * @throws ReflectionException
306 2
     */
307 2
    protected function spellcheckRetry(BaseQuery $query, SearchResult $searchResult)
308 2
    {
309 2
        $terms = $query->getTerms();
310
        $spellChecked = $searchResult->getCollatedSpellcheck();
311 2
        // Remove the fuzzyness from the collated check
312
        $term = preg_replace('/~\d+/', '', $spellChecked);
313
        $terms[0]['text'] = $term;
314
        $query->setTerms($terms);
315
        $this->retry = true;
316
317
        return $this->doSearch($query);
318
    }
319 10
320
    /**
321 10
     * Get all fields that are required for indexing in a unique way
322 10
     *
323 9
     * @return array
324
     */
325
    public function getFieldsForIndexing(): array
326
    {
327
        $facets = [];
328 10
        foreach ($this->getFacetFields() as $field) {
329 10
            $facets[] = $field['Field'];
330 10
        }
331 10
        // Return values to make the key reset
332 10
        // Only return unique values
333 10
        // And make it all a single array
334 10
        $fields = array_values(
335
            array_unique(
336
                array_merge(
337
                    $this->getFulltextFields(),
338
                    $this->getSortFields(),
339 10
                    $facets,
340
                    $this->getFilterFields()
341 10
                )
342
            )
343
        );
344
345
        $this->extend('updateFieldsForIndexing', $fields);
346
347
        return $fields;
348
    }
349 35
350
    /**
351
     * Upload config for this index to the given store
352
     *
353
     * @param ConfigStore $store
354 35
     */
355 35
    public function uploadConfig(ConfigStore $store): void
356 35
    {
357 35
        // @todo use types/schema/elevate rendering
358 35
        // Upload the config files for this index
359
        // Create a default schema which we can manage later
360
        $schema = (string)$this->schemaFactory->generateSchema();
361 35
        $store->uploadString(
362
            $this->getIndexName(),
363
            'schema.xml',
364 35
            $schema
365 35
        );
366 35
367
        $this->getSynonyms($store);
368
369 35
        // Upload additional files
370
        foreach (glob($this->schemaFactory->getExtrasPath() . '/*') as $file) {
371
            if (is_file($file)) {
372
                $store->uploadFile($this->getIndexName(), $file);
373
            }
374
        }
375
    }
376
377
    /**
378 35
     * Add synonyms. Public to be extendable
379
     *
380 35
     * @param ConfigStore $store Store to use to write synonyms
381
     * @param bool $defaults Include UK to US synonyms
382 35
     * @return string
383 35
     */
384 1
    public function getSynonyms($store = null, $defaults = true)
385
    {
386
        $synonyms = Synonyms::getSynonymsAsString($defaults);
387
        /** @var DataList|SearchSynonym[] $syn */
388 35
        $syn = SearchSynonym::get();
389 35
        foreach ($syn as $synonym) {
390 35
            $synonyms .= $synonym->getCombinedSynonym();
391 35
        }
392 35
393
        // Upload synonyms
394
        if ($store) {
395
            $store->uploadString(
396 35
                $this->getIndexName(),
397
                'synonyms.txt',
398
                $synonyms
399
            );
400
        }
401
402
        return $synonyms;
403
    }
404 2
405
    /**
406 2
     * Get the final, generated terms
407
     *
408
     * @return array
409
     */
410
    public function getQueryTerms(): array
411
    {
412
        return $this->queryTerms;
413
    }
414 1
415
    /**
416 1
     * Get the QueryComponentFactory. {@link QueryComponentFactory}
417
     *
418
     * @return QueryComponentFactory
419
     */
420
    public function getQueryFactory(): QueryComponentFactory
421
    {
422
        return $this->queryFactory;
423
    }
424
425
    /**
426
     * @return Query
427
     */
428
    public function getClientQuery(): Query
429
    {
430
        return $this->clientQuery;
431
    }
432
}
433