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

Command/IndexCreateCommand.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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'] = [
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