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

SwitchToNewAndRemoveOldIndex::estimate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 Matchish\ScoutElasticSearch\ElasticSearch\Index;
9
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Alias\Get;
10
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Alias\Update;
11
12
/**
13
 * @internal
14
 */
15
final class SwitchToNewAndRemoveOldIndex
16
{
17
    /**
18
     * @var Model
19
     */
20
    private $searchable;
21
    /**
22
     * @var Index
23
     */
24
    private $index;
25
26
    /**
27
     * @param Model $searchable
28
     */
29 10
    public function __construct(Model $searchable, Index $index)
30
    {
31 10
        $this->searchable = $searchable;
32 10
        $this->index = $index;
33 10
    }
34
35 9
    public function handle(Client $elasticsearch): void
36
    {
37
        /** @var Searchable $searchable */
38 9
        $searchable = $this->searchable;
39 9
        $params = Get::anyIndex($searchable->searchableAs());
40 9
        $response = $elasticsearch->indices()->getAliases($params->toArray());
41
42 9
        $params = new Update();
43 9
        foreach ($response as $indexName => $alias) {
44 9
            if ($indexName != $this->index->name()) {
45 2
                $params->removeIndex($indexName);
46
            } else {
47 9
                $params->add((string) $indexName, $searchable->searchableAs());
48
            }
49
        }
50 9
        $elasticsearch->indices()->updateAliases($params->toArray());
51 9
    }
52
53 8
    public function estimate(): int
54
    {
55 8
        return 1;
56
    }
57
58 8
    public function title(): string
59
    {
60 8
        return 'Switching to the new index';
61
    }
62
}
63