Passed
Pull Request — main (#67)
by Simon
02:48 queued 01:40
created

ElasticIndex::addFilterField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
/**
3
 * class ElasticIndex|Firesphere\ElasticSearch\Indexes\ElasticIndex is the base for indexing items
4
 *
5
 * @package Firesphere\Elastic\Search
6
 * @author Simon `Firesphere` Erkelens; Marco `Sheepy` Hermo
7
 * @copyright Copyright (c) 2018 - now() Firesphere & Sheepy
8
 */
9
10
namespace Firesphere\ElasticSearch\Indexes;
11
12
use Elastic\Elasticsearch\Exception\ClientResponseException;
13
use Elastic\Elasticsearch\Exception\MissingParameterException;
14
use Elastic\Elasticsearch\Exception\ServerResponseException;
15
use Firesphere\ElasticSearch\Queries\Builders\QueryBuilder;
16
use Firesphere\ElasticSearch\Queries\ElasticQuery;
17
use Firesphere\ElasticSearch\Results\SearchResult;
18
use Firesphere\ElasticSearch\Services\ElasticCoreService;
19
use Firesphere\ElasticSearch\Traits\IndexTraits\BaseIndexTrait;
0 ignored issues
show
Bug introduced by
The type Firesphere\ElasticSearch...exTraits\BaseIndexTrait was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use Firesphere\SearchBackend\Indexes\CoreIndex;
21
use Firesphere\SearchBackend\Traits\LoggerTrait;
22
use Firesphere\SearchBackend\Traits\QueryTraits\QueryFilterTrait;
23
use LogicException;
24
use Psr\Container\NotFoundExceptionInterface;
25
use SilverStripe\Control\HTTPRequest;
26
use SilverStripe\Core\Config\Configurable;
27
use SilverStripe\Core\Extensible;
28
use SilverStripe\Core\Injector\Injectable;
29
use SilverStripe\Core\Injector\Injector;
30
use SilverStripe\Dev\Deprecation;
31
32
/**
33
 * Base for managing a Elastic core.
34
 *
35
 * Base index settings and methods. Should be extended with at least a name for the index.
36
 * This is an abstract class that can not be instantiated on it's own
37
 *
38
 * @package Firesphere\Elastic\Search
39
 */
40
abstract class ElasticIndex extends CoreIndex
41
{
42
    use Extensible;
43
    use Configurable;
44
    use Injectable;
45
    use QueryFilterTrait;
46
    use BaseIndexTrait;
47
    use LoggerTrait;
48
49
    /**
50
     * @var array
51
     */
52
    protected $clientQuery;
53
    /**
54
     * @var array Fulltext fields
55
     */
56
    protected $fulltextFields = [];
57
    /**
58
     * @var array Filterable fields
59
     */
60
    protected $filterFields = [];
61
62
    /**
63
     * Set-up of core and fields through init
64
     * @throws NotFoundExceptionInterface
65
     */
66
    public function __construct()
67
    {
68
        $this->client = Injector::inst()->get(ElasticCoreService::class)->getClient();
69
70
        $this->extend('onBeforeInit');
71
        $this->init();
72
        $this->extend('onAfterInit');
73
    }
74
75
    /**
76
     * @param HTTPRequest $request
77
     * @return bool
78
     * @throws ClientResponseException
79
     * @throws MissingParameterException
80
     * @throws NotFoundExceptionInterface
81
     * @throws ServerResponseException
82
     */
83
    public function deleteIndex(HTTPRequest $request): bool
84
    {
85
        $deleteResult = false;
86
        if ($this->shouldClear($request) && $this->indexExists()) {
87
            $this->getLogger()->info(sprintf('Clearing index %s', $this->getIndexName()));
88
            $deleteResult = $this->client
89
                ->indices()
90
                ->delete(['index' => $this->getIndexName()])
91
                ->asBool();
0 ignored issues
show
Bug introduced by
The method asBool() does not exist on Http\Promise\Promise. ( Ignorable by Annotation )

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

91
                ->/** @scrutinizer ignore-call */ asBool();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
92
        }
93
94
        return $deleteResult;
95
    }
96
97
    /**
98
     * @param HTTPRequest $request
99
     * @return bool
100
     */
101
    private function shouldClear(HTTPRequest $request): bool
102
    {
103
        $var = $request->getVar('clear');
104
105
        return !empty($var);
106
    }
107
108
109
    /**
110
     * @return bool
111
     * @throws ClientResponseException
112
     * @throws MissingParameterException
113
     * @throws ServerResponseException
114
     */
115
    public function indexExists(): bool
116
    {
117
        return $this->getClient()
118
            ->indices()
119
            ->exists(['index' => $this->getIndexName()])
120
            ->asBool();
121
    }
122
123
    /**
124
     * {@inheritDoc}
125
     * @param ElasticQuery $query
126
     * @return SearchResult
127
     * @throws ClientResponseException
128
     * @throws ServerResponseException
129
     */
130
    public function doSearch($query)
131
    {
132
        $this->clientQuery = QueryBuilder::buildQuery($query, $this);
133
134
        $result = $this->client->search($this->clientQuery);
135
136
        return new SearchResult($result, $query, $this);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type Http\Promise\Promise; however, parameter $result of Firesphere\ElasticSearch...chResult::__construct() does only seem to accept Elastic\Elasticsearch\Response\Elasticsearch, maybe add an additional type check? ( Ignorable by Annotation )

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

136
        return new SearchResult(/** @scrutinizer ignore-type */ $result, $query, $this);
Loading history...
137
    }
138
139
    /**
140
     * Get current client query array
141
     * @return array
142
     */
143
    public function getClientQuery(): array
144
    {
145
        return $this->clientQuery;
146
    }
147
148
    /**
149
     * Gives the option to completely override the client query set
150
     *
151
     * @param array $clientQuery
152
     * @return void
153
     */
154
    public function setClientQuery(array $clientQuery): void
155
    {
156
        $this->clientQuery = $clientQuery;
157
    }
158
159
    /**
160
     * Add a single Fulltext field
161
     *
162
     * @param string $fulltextField
163
     * @param array $options
164
     * @return $this
165
     */
166
    public function addFulltextField($fulltextField, $options = []): self
167
    {
168
        $this->fulltextFields[] = $fulltextField;
169
170
        return $this;
171
    }
172
173
    /**
174
     * Add a filterable field
175
     * Compatibility stub for Solr
176
     *
177
     * @param $filterField
178
     * @return $this
179
     */
180
    public function addFilterField($filterField): self
181
    {
182
        $this->filterFields[] = $filterField;
183
        $this->addFulltextField($filterField);
184
185
        return $this;
186
    }
187
}
188