Completed
Pull Request — master (#1622)
by Rimas
10:50
created

PopulateCommand   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 247
Duplicated Lines 8.1 %

Coupling/Cohesion

Components 2
Dependencies 21

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 25
lcom 2
cbo 21
dl 20
loc 247
ccs 0
cts 116
cp 0
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 11 2
B execute() 0 48 11
A populateIndex() 0 19 3
B populateIndexType() 0 59 5
A refreshIndex() 0 6 1
A __construct() 20 20 2
A configure() 0 20 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
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 FOS\ElasticaBundle\Command;
13
14
use Elastica\Exception\Bulk\ResponseException as BulkResponseException;
15
use FOS\ElasticaBundle\Event\IndexPopulateEvent;
16
use FOS\ElasticaBundle\Event\TypePopulateEvent;
17
use FOS\ElasticaBundle\Index\IndexManager;
18
use FOS\ElasticaBundle\Index\Resetter;
19
use FOS\ElasticaBundle\Persister\Event\Events;
20
use FOS\ElasticaBundle\Persister\Event\OnExceptionEvent;
21
use FOS\ElasticaBundle\Persister\Event\PostAsyncInsertObjectsEvent;
22
use FOS\ElasticaBundle\Persister\Event\PostInsertObjectsEvent;
23
use FOS\ElasticaBundle\Persister\InPlacePagerPersister;
24
use FOS\ElasticaBundle\Persister\PagerPersisterInterface;
25
use FOS\ElasticaBundle\Persister\PagerPersisterRegistry;
26
use FOS\ElasticaBundle\Provider\PagerProviderRegistry;
27
use Symfony\Component\Console\Command\Command;
28
use Symfony\Component\Console\Helper\ProgressBar;
29
use Symfony\Component\Console\Helper\QuestionHelper;
30
use Symfony\Component\Console\Input\InputInterface;
31
use Symfony\Component\Console\Input\InputOption;
32
use Symfony\Component\Console\Output\OutputInterface;
33
use Symfony\Component\Console\Question\Question;
34
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
35
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
36
37
/**
38
 * Populate the search index.
39
 */
40
class PopulateCommand extends Command
41
{
42
    protected static $defaultName = 'fos:elastica:populate';
43
44
    /**
45
     * @var EventDispatcherInterface 
46
     */
47
    private $dispatcher;
48
49
    /**
50
     * @var IndexManager 
51
     */
52
    private $indexManager;
53
54
    /**
55
     * @var PagerProviderRegistry
56
     */
57
    private $pagerProviderRegistry;
58
59
    /**
60
     * @var PagerPersisterRegistry
61
     */
62
    private $pagerPersisterRegistry;
63
64
    /**
65
     * @var PagerPersisterInterface
66
     */
67
    private $pagerPersister;
68
69
    /**
70
     * @var Resetter
71
     */
72
    private $resetter;
73
74 View Code Duplication
    public function __construct(
75
        EventDispatcherInterface $dispatcher,
76
        IndexManager $indexManager,
77
        PagerProviderRegistry $pagerProviderRegistry,
78
        PagerPersisterRegistry $pagerPersisterRegistry,
79
        Resetter $resetter
80
    ) {
81
        parent::__construct();
82
83
        $this->dispatcher = $dispatcher;
84
85
        if (class_exists(LegacyEventDispatcherProxy::class)) {
86
            $this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
87
        }
88
89
        $this->indexManager = $indexManager;
90
        $this->pagerProviderRegistry = $pagerProviderRegistry;
91
        $this->pagerPersisterRegistry = $pagerPersisterRegistry;
92
        $this->resetter = $resetter;
93
    }
94
95
    protected function configure()
96
    {
97
        $this
98
            ->setName('fos:elastica:populate')
99
            ->addOption('index', null, InputOption::VALUE_OPTIONAL, 'The index to repopulate')
100
            ->addOption('type', null, InputOption::VALUE_OPTIONAL, 'The type to repopulate')
101
            ->addOption('no-reset', null, InputOption::VALUE_NONE, 'Do not reset index before populating')
102
            ->addOption('no-delete', null, InputOption::VALUE_NONE, 'Do not delete index after populate')
103
            ->addOption('sleep', null, InputOption::VALUE_REQUIRED, 'Sleep time between persisting iterations (microseconds)', 0)
104
            ->addOption('ignore-errors', null, InputOption::VALUE_NONE, 'Do not stop on errors')
105
            ->addOption('no-overwrite-format', null, InputOption::VALUE_NONE, 'Prevent this command from overwriting ProgressBar\'s formats')
106
107
            ->addOption('first-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page to start population from. Including the given page.', 1)
108
            ->addOption('last-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page to end population on. Including the given page.', null)
109
            ->addOption('max-per-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page size', 100)
110
            ->addOption('pager-persister', null, InputOption::VALUE_REQUIRED, 'The pager persister to be used to populate the index', InPlacePagerPersister::NAME)
111
112
            ->setDescription('Populates search indexes from providers')
113
        ;
114
    }
115
116
    protected function initialize(InputInterface $input, OutputInterface $output)
117
    {
118
        $this->pagerPersister = $this->pagerPersisterRegistry->getPagerPersister($input->getOption('pager-persister'));
119
120
        if (!$input->getOption('no-overwrite-format')) {
121
            ProgressBar::setFormatDefinition('normal', " %current%/%max% [%bar%] %percent:3s%%\n%message%");
122
            ProgressBar::setFormatDefinition('verbose', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%\n%message%");
123
            ProgressBar::setFormatDefinition('very_verbose', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%\n%message%");
124
            ProgressBar::setFormatDefinition('debug', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%\n%message%");
125
        }
126
    }
127
128
    protected function execute(InputInterface $input, OutputInterface $output)
129
    {
130
        $index = $input->getOption('index');
131
        $type = $input->getOption('type');
132
        $reset = !$input->getOption('no-reset');
133
        $delete = !$input->getOption('no-delete');
134
135
        $options = [
136
            'delete' => $delete,
137
            'reset' => $reset,
138
            'ignore_errors' => $input->getOption('ignore-errors'),
139
            'sleep' => $input->getOption('sleep'),
140
            'first_page' => $input->getOption('first-page'),
141
            'max_per_page' => $input->getOption('max-per-page'),
142
        ];
143
144
        if ($input->getOption('last-page')) {
145
            $options['last_page'] = $input->getOption('last-page');
146
        }
147
148
        if ($input->isInteractive() && $reset && 1 < $options['first_page']) {
149
            /** @var QuestionHelper $dialog */
150
            $dialog = $this->getHelperSet()->get('question');
151
            if (!$dialog->ask($input, $output, new Question('<question>You chose to reset the index and start indexing with an offset. Do you really want to do that?</question>'))) {
152
                return;
153
            }
154
        }
155
156
        if (null === $index && null !== $type) {
157
            throw new \InvalidArgumentException('Cannot specify type option without an index.');
158
        }
159
160
        if (null !== $index) {
161
            if (null !== $type) {
162
                $this->populateIndexType($output, $index, $type, $reset, $options);
163
            } else {
164
                $this->populateIndex($output, $index, $reset, $options);
165
            }
166
        } else {
167
            $indexes = array_keys($this->indexManager->getAllIndexes());
168
169
            foreach ($indexes as $index) {
170
                $this->populateIndex($output, $index, $reset, $options);
171
            }
172
        }
173
174
        return 0;
175
    }
176
177
    /**
178
     * Recreates an index, populates its types, and refreshes the index.
179
     *
180
     * @param OutputInterface $output
181
     * @param string          $index
182
     * @param bool            $reset
183
     * @param array           $options
184
     */
185
    private function populateIndex(OutputInterface $output, $index, $reset, $options)
186
    {
187
        $event = new IndexPopulateEvent($index, $reset, $options);
188
        $this->dispatcher->dispatch(IndexPopulateEvent::PRE_INDEX_POPULATE, $event);
189
190
        if ($event->isReset()) {
191
            $output->writeln(sprintf('<info>Resetting</info> <comment>%s</comment>', $index));
192
            $this->resetter->resetIndex($index, true);
193
        }
194
195
        $types = array_keys($this->pagerProviderRegistry->getIndexProviders($index));
196
        foreach ($types as $type) {
197
            $this->populateIndexType($output, $index, $type, false, $event->getOptions());
198
        }
199
200
        $this->dispatcher->dispatch(IndexPopulateEvent::POST_INDEX_POPULATE, $event);
201
202
        $this->refreshIndex($output, $index);
203
    }
204
205
    /**
206
     * Deletes/remaps an index type, populates it, and refreshes the index.
207
     *
208
     * @param OutputInterface $output
209
     * @param string          $index
210
     * @param string          $type
211
     * @param bool            $reset
212
     * @param array           $options
213
     */
214
    private function populateIndexType(OutputInterface $output, $index, $type, $reset, $options)
215
    {
216
        $event = new TypePopulateEvent($index, $type, $reset, $options);
217
        $this->dispatcher->dispatch(TypePopulateEvent::PRE_TYPE_POPULATE, $event);
218
219
        if ($event->isReset()) {
220
            $output->writeln(sprintf('<info>Resetting</info> <comment>%s/%s</comment>', $index, $type));
221
            $this->resetter->resetIndexType($index, $type);
222
        }
223
224
        $offset = 1 < $options['first_page'] ? ($options['first_page'] - 1) * $options['max_per_page'] : 0;
225
        $loggerClosure = ProgressClosureBuilder::build($output, 'Populating', $index, $type, $offset);
226
227
        $this->dispatcher->addListener(
228
            Events::ON_EXCEPTION,
229
            function(OnExceptionEvent $event) use ($loggerClosure) {
230
                $loggerClosure(
231
                    count($event->getObjects()),
232
                    $event->getPager()->getNbResults(),
233
                    sprintf('<error>%s</error>', $event->getException()->getMessage())
234
                );
235
            }
236
        );
237
238
        $this->dispatcher->addListener(
239
            Events::POST_INSERT_OBJECTS,
240
            function(PostInsertObjectsEvent $event) use ($loggerClosure) {
241
                $loggerClosure(count($event->getObjects()), $event->getPager()->getNbResults());
242
            }
243
        );
244
245
        $this->dispatcher->addListener(
246
            Events::POST_ASYNC_INSERT_OBJECTS,
247
            function(PostAsyncInsertObjectsEvent $event) use ($loggerClosure) {
248
                $loggerClosure($event->getObjectsCount(), $event->getPager()->getNbResults(), $event->getErrorMessage());
249
            }
250
        );
251
252
        if ($options['ignore_errors']) {
253
            $this->dispatcher->addListener(Events::ON_EXCEPTION, function(OnExceptionEvent $event) {
254
                if ($event->getException() instanceof BulkResponseException) {
255
                    $event->setIgnore(true);
256
                }
257
            });
258
        }
259
260
        $provider = $this->pagerProviderRegistry->getProvider($index, $type);
261
262
        $pager = $provider->provide($options);
263
264
        $options['indexName'] = $index;
265
        $options['typeName'] = $type;
266
267
        $this->pagerPersister->insert($pager, $options);
268
269
        $this->dispatcher->dispatch(TypePopulateEvent::POST_TYPE_POPULATE, $event);
270
271
        $this->refreshIndex($output, $index);
272
    }
273
274
    /**
275
     * Refreshes an index.
276
     *
277
     * @param OutputInterface $output
278
     * @param string          $index
279
     */
280
    private function refreshIndex(OutputInterface $output, $index)
281
    {
282
        $output->writeln(sprintf('<info>Refreshing</info> <comment>%s</comment>', $index));
283
        $this->indexManager->getIndex($index)->refresh();
284
        $output->writeln("");
285
    }
286
}
287