Completed
Pull Request — master (#95)
by
unknown
01:31
created

IndexDeleteCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 75
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B handle() 0 53 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cviebrock\LaravelElasticsearch\Console\Command;
6
7
use Elasticsearch\Client;
8
use Illuminate\Console\Command;
9
use Throwable;
10
11
final class IndexDeleteCommand extends Command
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $signature = 'laravel-elasticsearch:utils:index-delete
17
                            {index-name : The index name}';
18
19
    /**
20
     * @var Client
21
     */
22
    private $client;
23
24
    public function __construct(
25
        Client $client
26
    ) {
27
        $this->client = $client;
28
29
        parent::__construct();
30
    }
31
32
    public function handle(): int
33
    {
34
        $indexName = $this->argument('index-name');
35
36
        if ($indexName === null ||
37
            !is_string($indexName) ||
38
            mb_strlen($indexName) === 0
39
        ) {
40
            $this->output->writeln(
41
                '<error>Argument index-name must be a non empty string.</error>'
42
            );
43
44
            return self::FAILURE;
45
        }
46
47
        if (!$this->client->indices()->exists([
48
            'index' => $indexName,
49
        ])) {
50
            $this->output->writeln(
51
                sprintf(
52
                    '<error>Index %s doesn\'t exists and cannot be deleted.</error>',
53
                    $indexName
54
                )
55
            );
56
57
            return self::FAILURE;
58
        }
59
60
        try {
61
            $this->client->indices()->delete([
62
                'index' => $this->argument('index-name'),
63
            ]);
64
        } catch (Throwable $exception) {
65
            $this->output->writeln(
66
                sprintf(
67
                    '<error>Error deleting index %s, exception message: %s.</error>',
68
                    $indexName,
69
                    $exception->getMessage()
70
                )
71
            );
72
73
            return self::FAILURE;
74
        }
75
76
        $this->output->writeln(
77
            sprintf(
78
                '<info>Index %s deleted.</info>',
79
                $indexName
80
            )
81
        );
82
83
        return self::SUCCESS;
84
    }
85
}
86