ElasticIndex   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 147
rs 10
c 0
b 0
f 0
wmc 11

9 Methods

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

87
                ->/** @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...
88
        }
89
90
        return $deleteResult;
91
    }
92
93
    /**
94
     * @param HTTPRequest $request
95
     * @return bool
96
     */
97
    private function shouldClear(HTTPRequest $request): bool
98
    {
99
        $var = $request->getVar('clear');
100
101
        return !empty($var);
102
    }
103
104
105
    /**
106
     * @return bool
107
     * @throws ClientResponseException
108
     * @throws MissingParameterException
109
     * @throws ServerResponseException
110
     */
111
    public function indexExists(): bool
112
    {
113
        return $this->getClient()
114
            ->indices()
115
            ->exists(['index' => $this->getIndexName()])
116
            ->asBool();
117
    }
118
119
    /**
120
     * {@inheritDoc}
121
     * @param ElasticQuery $query
122
     * @return SearchResult
123
     * @throws ClientResponseException
124
     * @throws ServerResponseException
125
     */
126
    public function doSearch($query)
127
    {
128
        $this->clientQuery = QueryBuilder::buildQuery($query, $this);
129
130
        $result = $this->client->search($this->clientQuery);
131
132
        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

132
        return new SearchResult(/** @scrutinizer ignore-type */ $result, $query, $this);
Loading history...
133
    }
134
135
    /**
136
     * Get current client query array
137
     * @return array
138
     */
139
    public function getClientQuery(): array
140
    {
141
        return $this->clientQuery;
142
    }
143
144
    /**
145
     * Gives the option to completely override the client query set
146
     *
147
     * @param array $clientQuery
148
     * @return $this
149
     */
150
    public function setClientQuery(array $clientQuery): self
151
    {
152
        $this->clientQuery = $clientQuery;
153
154
        return $this;
155
    }
156
157
    /**
158
     * Add a filterable field
159
     * Compatibility stub for Solr
160
     *
161
     * @param $filterField
162
     * @return $this
163
     */
164
    public function addFilterField($filterField): self
165
    {
166
        $this->filterFields[] = $filterField;
167
        $this->addFulltextField($filterField);
168
169
        return $this;
170
    }
171
172
    /**
173
     * Add a single Fulltext field
174
     *
175
     * @param string $fulltextField
176
     * @param array $options
177
     * @return $this
178
     */
179
    public function addFulltextField($fulltextField, $options = []): self
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

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

179
    public function addFulltextField($fulltextField, /** @scrutinizer ignore-unused */ $options = []): self

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
180
    {
181
        $this->fulltextFields[] = $fulltextField;
182
183
        return $this;
184
    }
185
}
186