Passed
Pull Request — master (#15)
by Serhii
06:06
created

CleanUp::handle()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 16
ccs 12
cts 12
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 8
nop 1
crap 6
1
<?php
2
3
namespace Matchish\ScoutElasticSearch\Jobs\Stages;
4
5
use Elasticsearch\Client;
6
use Laravel\Scout\Searchable;
7
use Illuminate\Database\Eloquent\Model;
8
use Elasticsearch\Common\Exceptions\Missing404Exception;
9
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Alias\Get as GetAliasParams;
10
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Delete as DeleteIndexParams;
11
12
/**
13
 * @internal
14
 */
15
final class CleanUp
16
{
17
    /**
18
     * @var Model
19
     */
20
    private $searchable;
21
22
    /**
23
     * @param Model $searchable
24
     */
25 10
    public function __construct(Model $searchable)
26
    {
27 10
        $this->searchable = $searchable;
28 10
    }
29
30 9
    public function handle(Client $elasticsearch): void
31
    {
32
        /** @var Searchable $searchable */
33 9
        $searchable = $this->searchable;
34 9
        $params = GetAliasParams::anyIndex($searchable->searchableAs());
35
        try {
36 9
            $response = $elasticsearch->indices()->getAliases($params->toArray());
37 7
        } catch (Missing404Exception $e) {
38 7
            $response = [];
39
        }
40 9
        foreach ($response as $indexName => $data) {
41 2
            foreach ($data['aliases'] as $alias => $config) {
42 2
                if (array_key_exists('is_write_index', $config) && $config['is_write_index']) {
43 1
                    $params = new DeleteIndexParams((string) $indexName);
44 1
                    $elasticsearch->indices()->delete($params->toArray());
45 2
                    continue 2;
46
                }
47
            }
48
        }
49 9
    }
50
51 8
    public function title(): string
52
    {
53 8
        return 'Clean up';
54
    }
55
56 8
    public function estimate(): int
57
    {
58 8
        return 1;
59
    }
60
}
61