Completed
Push — master ( 1c1906...f16e7a )
by Colin
12s
created

CreateIndexCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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 (!$this->argumentIsValid($indexName)) {
37
            return self::FAILURE;
38
        }
39
40
        if ($this->client->indices()->exists([
41
            'index' => $indexName,
42
        ])) {
43
            $this->output->writeln(
44
                sprintf(
45
                    '<error>Index %s already exists and cannot be created.</error>',
46
                    $indexName
47
                )
48
            );
49
50
            return self::FAILURE;
51
        }
52
53
        try {
54
            $this->client->indices()->create([
55
                'index' => $indexName,
56
            ]);
57
        } catch (Throwable $exception) {
58
            $this->output->writeln(
59
                sprintf(
60
                    '<error>Error creating index %s, exception message: %s.</error>',
61
                    $indexName,
62
                    $exception->getMessage()
63
                )
64
            );
65
66
            return self::FAILURE;
67
        }
68
69
        $this->output->writeln(
70
            sprintf(
71
                '<info>Index %s created.</info>',
72
                $indexName
73
            )
74
        );
75
76
        return self::SUCCESS;
77
    }
78
79
    private function argumentIsValid($indexName): bool
80
    {
81
        if ($indexName === null ||
82
            !is_string($indexName) ||
83
            mb_strlen($indexName) === 0
84
        ) {
85
            $this->output->writeln(
86
                '<error>Argument index-name must be a non empty string.</error>'
87
            );
88
89
            return false;
90
        }
91
92
        return true;
93
    }
94
}
95