Completed
Pull Request — master (#94)
by
unknown
01:15
created

CreateIndexCommand::handle()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 8.9688
c 0
b 0
f 0
cc 5
nc 3
nop 0
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 CreateIndexCommand extends Command
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $signature = 'laravel-elasticsearch:utils:index-create
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
        try {
48
            $this->client->indices()->create([
49
                'index' => $indexName,
50
            ]);
51
        } catch (Throwable $exception) {
52
            $this->output->writeln(
53
                sprintf(
54
                    '<error>Error creating index %s, exception message: %s.</error>',
55
                    $indexName,
56
                    $exception->getMessage()
57
                )
58
            );
59
60
            return self::FAILURE;
61
        }
62
63
        $this->output->writeln(
64
            sprintf(
65
                '<info>Index %s created.</info>',
66
                $indexName
67
            )
68
        );
69
70
        return self::SUCCESS;
71
    }
72
}
73