Completed
Pull Request — master (#710)
by
unknown
02:28
created

IndexCreateCommand::execute()   C

Complexity

Conditions 9
Paths 11

Size

Total Lines 81
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 81
rs 5.5727
c 0
b 0
f 0
cc 9
eloc 47
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
    /**
26
     * {@inheritdoc}
27
     */
28
    protected function configure()
29
    {
30
        parent::configure();
31
32
        $this
33
            ->setName('ongr:es:index:create')
34
            ->setDescription('Creates elasticsearch index.')
35
            ->addOption('time', 't', InputOption::VALUE_NONE, 'Adds date suffix to the new index name')
36
            ->addOption(
37
                'alias',
38
                'a',
39
                InputOption::VALUE_NONE,
40
                'If the time suffix is used, its nice to create an alias to the configured index name.'
41
            )
42
            ->addOption(
43
                'no-mapping',
44
                null,
45
                InputOption::VALUE_NONE,
46
                'Do not include mapping'
47
            )
48
            ->addOption(
49
                'no-array-mappings',
50
                null,
51
                InputOption::VALUE_NONE,
52
                'Do not include array mapping'
53
            )
54
            ->addOption(
55
                'if-not-exists',
56
                null,
57
                InputOption::VALUE_NONE,
58
                'Don\'t trigger an error, when the index already exists'
59
            )
60
            ->addOption('dump', null, InputOption::VALUE_NONE, 'Prints out index mapping json');
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function execute(InputInterface $input, OutputInterface $output)
67
    {
68
        $io = new SymfonyStyle($input, $output);
69
        $manager = $this->getManager($input->getOption('manager'));
70
        $originalIndexName = $manager->getIndexName();
71
72
        if ($input->getOption('dump')) {
73
            $io->note("Index mappings:");
74
            $io->text(
75
                json_encode(
76
                    $manager->getIndexMappings(),
77
                    JSON_PRETTY_PRINT
78
                )
79
            );
80
81
            return 0;
82
        }
83
84
        if ($input->getOption('time')) {
85
            /** @var IndexSuffixFinder $finder */
86
            $finder = $this->getContainer()->get('es.client.index_suffix_finder');
87
            $finder->setNextFreeIndex($manager);
88
        }
89
90
        if ($input->getOption('if-not-exists') && $manager->indexExists()) {
91
            $io->note(
92
                sprintf(
93
                    'Index `%s` already exists in `%s` manager.',
94
                    $manager->getIndexName(),
95
                    $input->getOption('manager')
96
                )
97
            );
98
99
            return 0;
100
        }
101
102
        $manager->createIndex($input->getOption('no-mapping'), $input->getOption('no-array-mappings'));
103
104
        $io->text(
105
            sprintf(
106
                'Created `<comment>%s</comment>` index for the `<comment>%s</comment>` manager. ',
107
                $manager->getIndexName(),
108
                $input->getOption('manager')
109
            )
110
        );
111
112
        if ($input->getOption('alias') && $originalIndexName != $manager->getIndexName()) {
113
            $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...
114
                'actions' => [
115
                    [
116
                        'add' => [
117
                            'index' => $manager->getIndexName(),
118
                            'alias' => $originalIndexName,
119
                        ]
120
                    ]
121
                ]
122
            ];
123
            $message = 'Created an alias `<comment>'.$originalIndexName.'</comment>` for the `<comment>'.
124
                $manager->getIndexName().'</comment>` index. ';
125
126
            if ($manager->getClient()->indices()->existsAlias(['name' => $originalIndexName])) {
127
                $currentAlias = $manager->getClient()->indices()->getAlias(
128
                    [
129
                        'name' => $originalIndexName,
130
                    ]
131
                );
132
133
                $indexesToRemoveAliases = implode(',', array_keys($currentAlias));
134
                if (!empty($indexesToRemoveAliases)) {
135
                    $params['body']['actions'][]['remove'] = [
136
                            'index' => $indexesToRemoveAliases,
137
                            'alias' => $originalIndexName,
138
                        ];
139
                    $message .= 'Removed `<comment>'.$originalIndexName.'</comment>` alias from `<comment>'.
140
                        $indexesToRemoveAliases.'</comment>` index(es).';
141
                }
142
            }
143
            $manager->getClient()->indices()->updateAliases($params);
144
            $io->text($message);
145
        }
146
    }
147
}
148