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

CreateIndexCommand::handle()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 8.4032
c 0
b 0
f 0
cc 6
nc 4
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        if ($this->client->indices()->exists([
48
            'index' => $indexName,
49
        ])) {
50
            $this->output->writeln(
51
                sprintf(
52
                    '<error>Index %s already exists and cannot be created.</error>',
53
                    $indexName
54
                )
55
            );
56
57
            return self::FAILURE;
58
        }
59
60
        try {
61
            $this->client->indices()->create([
62
                'index' => $indexName,
63
            ]);
64
        } catch (Throwable $exception) {
65
            $this->output->writeln(
66
                sprintf(
67
                    '<error>Error creating 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 created.</info>',
79
                $indexName
80
            )
81
        );
82
83
        return self::SUCCESS;
84
    }
85
}
86