Completed
Push — master ( 422041...41a1ad )
by Simonas
17:36
created

IndexCreateCommand::execute()   C

Complexity

Conditions 9
Paths 11

Size

Total Lines 81

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 81
rs 6.8589
c 0
b 0
f 0
cc 9
nc 11
nop 2

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
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Command;
13
14
use ONGR\ElasticsearchBundle\Service\IndexSuffixFinder;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\Console\Style\SymfonyStyle;
19
20
/**
21
 * Command for creating elasticsearch index.
22
 */
23
class IndexCreateCommand extends AbstractManagerAwareCommand
24
{
25
    public static $defaultName = 'ongr:es:index:create';
26
27
    /**
28
     * {@inheritdoc}
29
     */
30 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
31
    {
32
        parent::configure();
33
34
        $this
35
            ->setName(static::$defaultName)
36
            ->setDescription('Creates elasticsearch index.')
37
            ->addOption('time', 't', InputOption::VALUE_NONE, 'Adds date suffix to the new index name')
38
            ->addOption(
39
                'alias',
40
                'a',
41
                InputOption::VALUE_NONE,
42
                'If the time suffix is used, its nice to create an alias to the configured index name.'
43
            )
44
            ->addOption('no-mapping', null, InputOption::VALUE_NONE, 'Do not include mapping')
45
            ->addOption(
46
                'if-not-exists',
47
                null,
48
                InputOption::VALUE_NONE,
49
                'Don\'t trigger an error, when the index already exists'
50
            )
51
            ->addOption('dump', null, InputOption::VALUE_NONE, 'Prints out index mapping json');
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    protected function execute(InputInterface $input, OutputInterface $output)
58
    {
59
        $io = new SymfonyStyle($input, $output);
60
        $manager = $this->getManager($input->getOption('manager'));
61
        $originalIndexName = $manager->getIndexName();
62
63
        if ($input->getOption('dump')) {
64
            $io->note("Index mappings:");
65
            $io->text(
66
                json_encode(
67
                    $manager->getIndexMappings(),
68
                    JSON_PRETTY_PRINT
69
                )
70
            );
71
72
            return 0;
73
        }
74
75
        if ($input->getOption('time')) {
76
            /** @var IndexSuffixFinder $finder */
77
            $finder = $this->getContainer()->get('es.client.index_suffix_finder');
78
            $finder->setNextFreeIndex($manager);
79
        }
80
81
        if ($input->getOption('if-not-exists') && $manager->indexExists()) {
82
            $io->note(
83
                sprintf(
84
                    'Index `%s` already exists in `%s` manager.',
85
                    $manager->getIndexName(),
86
                    $input->getOption('manager')
87
                )
88
            );
89
90
            return 0;
91
        }
92
93
        $manager->createIndex($input->getOption('no-mapping'));
94
95
        $io->text(
96
            sprintf(
97
                'Created `<comment>%s</comment>` index for the `<comment>%s</comment>` manager. ',
98
                $manager->getIndexName(),
99
                $input->getOption('manager')
100
            )
101
        );
102
103
        if ($input->getOption('alias') && $originalIndexName != $manager->getIndexName()) {
104
            $params['body'] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
105
                'actions' => [
106
                    [
107
                        'add' => [
108
                            'index' => $manager->getIndexName(),
109
                            'alias' => $originalIndexName,
110
                        ]
111
                    ]
112
                ]
113
            ];
114
            $message = 'Created an alias `<comment>'.$originalIndexName.'</comment>` for the `<comment>'.
115
                $manager->getIndexName().'</comment>` index. ';
116
117
            if ($manager->getClient()->indices()->existsAlias(['name' => $originalIndexName])) {
118
                $currentAlias = $manager->getClient()->indices()->getAlias(
119
                    [
120
                        'name' => $originalIndexName,
121
                    ]
122
                );
123
124
                $indexesToRemoveAliases = implode(',', array_keys($currentAlias));
125
                if (!empty($indexesToRemoveAliases)) {
126
                    $params['body']['actions'][]['remove'] = [
127
                            'index' => $indexesToRemoveAliases,
128
                            'alias' => $originalIndexName,
129
                        ];
130
                    $message .= 'Removed `<comment>'.$originalIndexName.'</comment>` alias from `<comment>'.
131
                        $indexesToRemoveAliases.'</comment>` index(es).';
132
                }
133
            }
134
            $manager->getClient()->indices()->updateAliases($params);
135
            $io->text($message);
136
        }
137
    }
138
}
139