Completed
Push — master ( 6ac691...6b4094 )
by Avtandil
02:36
created

ElasticSearchManager::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Laravel Lodash package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
12
namespace Longman\LaravelLodash\ElasticSearch;
13
14
use ElasticSearch\Client;
15
use InvalidArgumentException;
16
use RuntimeException;
17
18
class ElasticSearchManager implements ElasticSearchManagerContract
19
{
20
    /**
21
     * @var \ElasticSearch\Client
22
     */
23
    protected $client;
24
25
    /**
26
     * @var bool
27
     */
28
    protected $enabled;
29
30
    /**
31
     * @var int|null
32
     */
33
    protected $timeout;
34
35
    public function __construct(Client $client, bool $enabled = false)
36
    {
37
        $this->client = $client;
38
        $this->enabled = $enabled;
39
    }
40
41
    public function setEnabled(bool $enabled): ElasticSearchManagerContract
42
    {
43
        $this->enabled = $enabled;
44
45
        return $this;
46
    }
47
48
    public function setTimeout(int $timeout): ElasticSearchManagerContract
49
    {
50
        $this->timeout = $timeout;
51
52
        return $this;
53
    }
54
55
    public function createIndex(string $index_name, array $settings, array $mappings)
56
    {
57
        if (! $this->isEnabled()) {
58
            return;
59
        }
60
61
        $params = [
62
            'index' => $index_name,
63
            'body'  => [
64
                'settings' => $settings,
65
                'mappings' => $mappings,
66
            ],
67
        ];
68
69
        if (! empty($this->timeout)) {
70
            $params['client'] = [
71
                'timeout' => $this->timeout,
72
            ];
73
        }
74
75
        $response = $this->client->indices()->create($params);
76
77
        if ($response['acknowledged'] !== true) {
78
            throw new RuntimeException('Something went wrong during index creation');
79
        }
80
    }
81
82
    public function deleteIndexes(array $names)
83
    {
84
        if (! $this->isEnabled()) {
85
            return;
86
        }
87
        if (empty($names)) {
88
            throw new InvalidArgumentException('Index names can not be empty');
89
        }
90
91
        $params = [
92
            'index' => implode(',', $names),
93
        ];
94
95
        if (! empty($this->timeout)) {
96
            $params['client'] = [
97
                'timeout' => $this->timeout,
98
            ];
99
        }
100
101
        $response = $this->client->indices()->delete($params);
102
        if ($response['acknowledged'] !== true) {
103
            throw new RuntimeException('Something went wrong during index deletion');
104
        }
105
    }
106
107
    public function deleteIndexesByAlias(string $alias_name)
108
    {
109
        if (! $this->isEnabled()) {
110
            return;
111
        }
112
113
        $params = [
114
            'name' => $alias_name,
115
        ];
116
117
        $response = $this->client->indices()->getAlias($params);
118
        if (empty($response)) {
119
            throw new RuntimeException('Can not get alias ' . $alias_name);
120
        }
121
122
        $indexes = array_keys($response);
123
        $this->deleteIndexes($indexes);
124
    }
125
126 View Code Duplication
    public function addDocumentsToIndex(string $index_name, string $type_name, array $items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127
    {
128
        if (! $this->isEnabled()) {
129
            return;
130
        }
131
132
        $params = [
133
            'body' => [],
134
        ];
135
136
        if (! empty($this->timeout)) {
137
            $params['client'] = [
138
                'timeout' => $this->timeout,
139
            ];
140
        }
141
142
        foreach ($items as $id => $item) {
143
            $params['body'][] = [
144
                'create' => [
145
                    '_index' => $index_name,
146
                    '_type'  => $type_name,
147
                    '_id'    => $id,
148
                ],
149
            ];
150
151
            $params['body'][] = $item;
152
        }
153
154
        $responses = $this->client->bulk($params);
155
        if ($responses['errors'] === true) {
156
            throw new RuntimeException('Error occurred during bulk insert');
157
        }
158
    }
159
160 View Code Duplication
    public function updateDocumentsInIndex(string $index_name, string $type_name, array $items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
    {
162
        if (! $this->isEnabled()) {
163
            return;
164
        }
165
166
        $params = [
167
            'body' => [],
168
        ];
169
170
        if (! empty($this->timeout)) {
171
            $params['client'] = [
172
                'timeout' => $this->timeout,
173
            ];
174
        }
175
176
        foreach ($items as $id => $item) {
177
            $params['body'][] = [
178
                'update' => [
179
                    '_index' => $index_name,
180
                    '_type'  => $type_name,
181
                    '_id'    => $id,
182
                ],
183
            ];
184
185
            $params['body'][] = ['doc' => $item];
186
        }
187
188
        $responses = $this->client->bulk($params);
189
        if ($responses['errors'] === true) {
190
            throw new RuntimeException('Error occurred during bulk insert');
191
        }
192
    }
193
194 View Code Duplication
    public function refreshIndex(string $index_name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
195
    {
196
        if (! $this->isEnabled()) {
197
            return;
198
        }
199
200
        $params = [
201
            'index' => $index_name,
202
        ];
203
204
        if (! empty($this->timeout)) {
205
            $params['client'] = [
206
                'timeout' => $this->timeout,
207
            ];
208
        }
209
210
        $this->client->indices()->refresh($params);
211
    }
212
213 View Code Duplication
    public function performSearch(ElasticSearchQueryContract $query): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
    {
215
        if (! $this->isEnabled()) {
216
            return [];
217
        }
218
219
        $params = $query->build();
220
        if (! empty($this->timeout)) {
221
            $params['client'] = [
222
                'timeout' => $this->timeout,
223
            ];
224
        }
225
226
        $results = $this->client->search($params);
227
228
        return $results;
229
    }
230
231
    public function switchIndexAlias(string $alias_name, string $index_name)
232
    {
233
        if (! $this->isEnabled()) {
234
            return;
235
        }
236
237
        $params = [
238
            'name' => $alias_name,
239
        ];
240
241
        $exists = $this->client->indices()->existsAlias($params);
242
243
        $actions = [];
244
        // If alias already exists remove from indexes
245
        if ($exists) {
246
            $params = [
247
                'name' => $alias_name,
248
            ];
249
250
            $response = $this->client->indices()->getAlias($params);
251
            if (empty($response)) {
252
                throw new RuntimeException('Can not get alias ' . $alias_name);
253
            }
254
255
            $indexes = array_keys($response);
256
257
            foreach ($indexes as $index) {
258
                $actions[] = [
259
                    'remove' => [
260
                        'index' => $index,
261
                        'alias' => $alias_name,
262
                    ],
263
                ];
264
            }
265
        }
266
267
        $actions[] = [
268
            'add' => [
269
                'index' => $index_name,
270
                'alias' => $alias_name,
271
            ],
272
        ];
273
274
        $params = [
275
            'body' => [
276
                'actions' => $actions,
277
            ],
278
        ];
279
280
        $response = $this->client->indices()->updateAliases($params);
281
        if ($response['acknowledged'] !== true) {
282
            throw new RuntimeException('Switching alias response error');
283
        }
284
    }
285
286
    public function createTemplate(string $name, array $settings)
287
    {
288
        if (! $this->isEnabled()) {
289
            return;
290
        }
291
292
        $params = [
293
            'name' => $name,
294
            'body' => $settings,
295
        ];
296
297
        if (! empty($this->timeout)) {
298
            $params['client'] = [
299
                'timeout' => $this->timeout,
300
            ];
301
        }
302
303
        $response = $this->client->indices()->putTemplate($params);
304
305
        if ($response['acknowledged'] !== true) {
306
            throw new RuntimeException('Something went wrong during template creation');
307
        }
308
    }
309
310
    public function ping(): bool
311
    {
312
        if (! $this->isEnabled()) {
313
            return false;
314
        }
315
316
        return $this->client->ping();
317
    }
318
319
    public function getClient(): Client
320
    {
321
        return $this->client;
322
    }
323
324
    public function isEnabled(): bool
325
    {
326
        return $this->enabled;
327
    }
328
}
329