Passed
Push — dev ( f797db...f96251 )
by Darko
06:46
created

ElasticSearchSiteSearch::indexSearch()   A

Complexity

Conditions 5
Paths 19

Size

Total Lines 51
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 3 Features 0
Metric Value
eloc 30
c 7
b 3
f 0
dl 0
loc 51
rs 9.1288
cc 5
nc 19
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Blacklight;
4
5
use App\Models\Release;
6
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Str;
9
use sspat\ESQuerySanitizer\Sanitizer;
10
11
class ElasticSearchSiteSearch
12
{
13
    /**
14
     * @param string|array $phrases
15
     * @param int $limit
16
     * @return mixed
17
     */
18
    public function indexSearch($phrases, int $limit)
19
    {
20
        $keywords = $this->sanitize($phrases);
21
        try {
22
            $search = [
23
                'scroll' => '30s',
24
                'index' => 'releases',
25
                'body' => [
26
                    'query' => [
27
                        'query_string' => [
28
                            'query' => $keywords,
29
                            'fields' => ['searchname', 'plainsearchname', 'fromname', 'filename', 'name'],
30
                            'analyze_wildcard' => true,
31
                            'default_operator' => 'and',
32
                        ],
33
                    ],
34
                    'size' => $limit,
35
                    'sort' => [
36
                        'add_date' => [
37
                            'order' => 'desc',
38
                        ],
39
                        'post_date' => [
40
                            'order' => 'desc',
41
                        ],
42
                    ],
43
                ],
44
            ];
45
46
            $results = \Elasticsearch::search($search);
47
48
            $searchResult = [];
49
            while (isset($results['hits']['hits']) && count($results['hits']['hits']) > 0) {
50
                foreach ($results['hits']['hits'] as $result) {
51
                    $searchResult[] = $result['_source']['id'];
52
                }
53
54
                // When done, get the new scroll_id
55
                // You must always refresh your _scroll_id!  It can change sometimes
56
                $scroll_id = $results['_scroll_id'];
57
58
                // Execute a Scroll request and repeat
59
                $results = \Elasticsearch::scroll([
60
                    'scroll_id' => $scroll_id,  //...using our previously obtained _scroll_id
61
                    'scroll' => '30s',        // and the same timeout window
62
                ]
63
            );
64
            }
65
66
            return $searchResult;
67
        } catch (BadRequest400Exception $request400Exception) {
68
            return [];
69
        }
70
    }
71
72
    /**
73
     * @param string|array $searchName
74
     * @param int $limit
75
     * @return array
76
     */
77
    public function indexSearchApi($searchName, int $limit)
78
    {
79
        $keywords = $this->sanitize($searchName);
80
        try {
81
            $search = [
82
                'scroll' => '30s',
83
                'index' => 'releases',
84
                'body' => [
85
                    'query' => [
86
                        'query_string' => [
87
                            'query' => $keywords,
88
                            'fields' => ['searchname', 'plainsearchname'],
89
                            'analyze_wildcard' => true,
90
                            'default_operator' => 'and',
91
                        ],
92
                    ],
93
                    'size' => $limit,
94
                    'sort' => [
95
                        'add_date' => [
96
                            'order' => 'desc',
97
                        ],
98
                        'post_date' => [
99
                            'order' => 'desc',
100
                        ],
101
                    ],
102
                ],
103
            ];
104
105
            $results = \Elasticsearch::search($search);
106
107
            $searchResult = [];
108
            while (isset($results['hits']['hits']) && count($results['hits']['hits']) > 0) {
109
                foreach ($results['hits']['hits'] as $result) {
110
                    $searchResult[] = $result['_source']['id'];
111
                }
112
113
                // When done, get the new scroll_id
114
                // You must always refresh your _scroll_id!  It can change sometimes
115
                $scroll_id = $results['_scroll_id'];
116
117
                // Execute a Scroll request and repeat
118
                $results = \Elasticsearch::scroll([
119
                    'scroll_id' => $scroll_id,  //...using our previously obtained _scroll_id
120
                    'scroll' => '30s',        // and the same timeout window
121
                ]
122
                );
123
            }
124
125
            return $searchResult;
126
        } catch (BadRequest400Exception $request400Exception) {
127
            return [];
128
        }
129
    }
130
131
    /**
132
     * Search function used in TV, TV API, Movies and Anime searches.
133
     * @param string|array $name
134
     * @param int $limit
135
     * @return array
136
     */
137
    public function indexSearchTMA($name, $limit)
138
    {
139
        $keywords = $this->sanitize($name);
140
        try {
141
            $search = [
142
                'scroll' => '30s',
143
                'index' => 'releases',
144
                'body' => [
145
                    'query' => [
146
                        'query_string' => [
147
                            'query' => $keywords,
148
                            'fields' => ['searchname', 'plainsearchname'],
149
                            'analyze_wildcard' => true,
150
                            'default_operator' => 'and',
151
                        ],
152
                    ],
153
                    'size' => $limit,
154
                    'sort' => [
155
                        'add_date' => [
156
                            'order' =>'desc',
157
                        ],
158
                        'post_date' => [
159
                            'order' => 'desc',
160
                        ],
161
                    ],
162
                ],
163
            ];
164
165
            $results = \Elasticsearch::search($search);
166
167
            $searchResult = [];
168
            while (isset($results['hits']['hits']) && count($results['hits']['hits']) > 0) {
169
                foreach ($results['hits']['hits'] as $result) {
170
                    $searchResult[] = $result['_source']['id'];
171
                }
172
173
                // When done, get the new scroll_id
174
                // You must always refresh your _scroll_id!  It can change sometimes
175
                $scroll_id = $results['_scroll_id'];
176
177
                // Execute a Scroll request and repeat
178
                $results = \Elasticsearch::scroll([
179
                    'scroll_id' => $scroll_id,  //...using our previously obtained _scroll_id
180
                    'scroll'    => '30s',        // and the same timeout window
181
                ]
182
                );
183
            }
184
185
            return $searchResult;
186
        } catch (BadRequest400Exception $request400Exception) {
187
            return [];
188
        }
189
    }
190
191
    /**
192
     * @param string|array $search
193
     * @return array|\Illuminate\Support\Collection
194
     */
195
    public function predbIndexSearch($search)
196
    {
197
        try {
198
            $search = [
199
                'scroll' => '30s',
200
                'index' => 'predb',
201
                'body' => [
202
                    'query' => [
203
                        'query_string' => [
204
                            'query' => $search,
205
                            'fields' => ['title'],
206
                            'analyze_wildcard' => true,
207
                            'default_operator' => 'and',
208
                        ],
209
                    ],
210
                    'size' => 1000,
211
                ],
212
            ];
213
214
            $results = \Elasticsearch::search($search);
215
216
            $ids = [];
217
            while (isset($results['hits']['hits']) && count($results['hits']['hits']) > 0) {
218
                foreach ($results['hits']['hits'] as $result) {
219
                    $ids[] = $result['_source']['id'];
220
                }
221
                if (empty($ids)) {
222
                    return collect();
223
                }
224
                // When done, get the new scroll_id
225
                // You must always refresh your _scroll_id!  It can change sometimes
226
                $scroll_id = $results['_scroll_id'];
227
228
                // Execute a Scroll request and repeat
229
                $results = \Elasticsearch::scroll([
230
                    'scroll_id' => $scroll_id,  //...using our previously obtained _scroll_id
231
                    'scroll' => '30s',        // and the same timeout window
232
                ]
233
                );
234
            }
235
236
            return $ids;
237
        } catch (BadRequest400Exception $request400Exception) {
238
            return [];
239
        }
240
    }
241
242
    /**
243
     * @param array $parameters
244
     */
245
    public function insertRelease(array $parameters): void
246
    {
247
        $searchNameDotless = str_replace(['.', '-'], ' ', $parameters['searchname']);
248
        $data = [
249
            'body' => [
250
                'id' => $parameters['id'],
251
                'name' => $parameters['name'],
252
                'searchname' => $parameters['searchname'],
253
                'plainsearchname' => $searchNameDotless,
254
                'fromname' => $parameters['fromname'],
255
                'filename' => $parameters['filename'] ?? '',
256
                'add_date' => now()->format('Y-m-d H:i:s'),
257
                'post_date' => $parameters['postdate'],
258
            ],
259
            'index' => 'releases',
260
            'id' => $parameters['id'],
261
        ];
262
263
        \Elasticsearch::index($data);
264
    }
265
266
    /**
267
     * @param int $id
268
     */
269
    public function updateRelease(int $id)
270
    {
271
        $new = Release::query()
272
            ->where('releases.id', $id)
273
            ->leftJoin('release_files as rf', 'releases.id', '=', 'rf.releases_id')
274
            ->select(['releases.id', 'releases.name', 'releases.searchname', 'releases.fromname', DB::raw('IFNULL(GROUP_CONCAT(rf.name SEPARATOR " "),"") filename')])
275
            ->groupBy('releases.id')
276
            ->first();
277
        if ($new !== null) {
278
            $searchNameDotless = str_replace(['.', '-'], ' ', $new->searchname);
279
            $data = [
280
                'body' => [
281
                    'doc' => [
282
                        'id' => $new->id,
283
                        'name' => $new->name,
284
                        'searchname' => $new->searchname,
285
                        'plainsearchname' => $searchNameDotless,
286
                        'fromname' => $new->fromname,
287
                        'filename' => $new->filename,
0 ignored issues
show
Bug introduced by
The property filename does not seem to exist on App\Models\Release. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
288
                    ],
289
                    'doc_as_upsert' => true,
290
                ],
291
292
                'index' => 'releases',
293
                'id' => $new->id,
294
            ];
295
296
            \Elasticsearch::update($data);
297
        }
298
    }
299
300
    /**
301
     * @param $searchTerm
302
     * @return array
303
     */
304
    public function searchPreDb($searchTerm)
305
    {
306
        $search = [
307
            'index' => 'predb',
308
            'body' => [
309
                'query' => [
310
                    'query_string' => [
311
                        'query' => $searchTerm,
312
                        'fields' => ['title', 'filename'],
313
                        'analyze_wildcard' => true,
314
                        'default_operator' => 'and',
315
                    ],
316
                ],
317
            ],
318
        ];
319
320
        try {
321
            $primaryResults = \Elasticsearch::search($search);
322
323
            $results = [];
324
            foreach ($primaryResults['hits']['hits'] as $primaryResult) {
325
                $results[] = $primaryResult['_source'];
326
            }
327
        } catch (BadRequest400Exception $badRequest400Exception) {
328
            return [];
329
        }
330
331
        return $results;
332
    }
333
334
    /**
335
     * @param $parameters
336
     */
337
    public function insertPreDb($parameters)
338
    {
339
        $data = [
340
            'body' => [
341
                'id' => $parameters['id'],
342
                'title' => $parameters['title'],
343
                'source' => $parameters['source'],
344
                'filename' => $parameters['filename'],
345
            ],
346
            'index' => 'predb',
347
            'id' => $parameters['id'],
348
        ];
349
350
        \Elasticsearch::index($data);
351
    }
352
353
    /**
354
     * @param $parameters
355
     */
356
    public function updatePreDb($parameters)
357
    {
358
        $data = [
359
            'body' => [
360
                'doc' => [
361
                    'id' => $parameters['id'],
362
                    'title' => $parameters['title'],
363
                    'filename' => $parameters['filename'],
364
                    'source' => $parameters['source'],
365
                ],
366
                'doc_as_upsert' => true,
367
            ],
368
369
            'index' => 'predb',
370
            'id' => $parameters['id'],
371
        ];
372
373
        \Elasticsearch::update($data);
374
    }
375
376
    /**
377
     * @param array|string $phrases
378
     * @return string
379
     */
380
    private function sanitize($phrases): string
381
    {
382
        if (! is_array($phrases)) {
383
            $wordArray = explode(' ', str_replace('.', ' ', $phrases));
384
        } else {
385
            $wordArray = $phrases;
386
        }
387
        $keywords = [];
388
        foreach ($wordArray as $words) {
389
            $tempWords = [];
390
            $words = preg_split('/\s+/', $words);
391
            foreach ($words as $st) {
392
                if (Str::startsWith($st, ['!', '+', '-', '?', '*']) && Str::length($st) > 1 && ! preg_match('/(!|\+|\?|-|\*){2,}/', $st)) {
393
                    $str = $st;
394
                } elseif (Str::endsWith($st, ['+', '-', '?', '*']) && Str::length($st) > 1 && ! preg_match('/(!|\+|\?|-|\*){2,}/', $st)) {
395
                    $str = $st;
396
                } else {
397
                    $str = Sanitizer::escape($st);
398
                }
399
                $tempWords[] = $str;
400
            }
401
402
            $keywords = $tempWords;
403
        }
404
405
        return implode(' ', $keywords);
406
    }
407
}
408