Completed
Push — master ( 80d3da...0d64d6 )
by Karel
14s
created

PopulateCommand::populateIndex()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 0
cts 38
cp 0
rs 8.627
c 0
b 0
f 0
cc 5
nc 8
nop 4
crap 30

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 FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <https://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\PostIndexPopulateEvent;
16
use FOS\ElasticaBundle\Event\PreIndexPopulateEvent;
17
use FOS\ElasticaBundle\Index\IndexManager;
18
use FOS\ElasticaBundle\Index\Resetter;
19
use FOS\ElasticaBundle\Persister\Event\OnExceptionEvent;
20
use FOS\ElasticaBundle\Persister\Event\PostAsyncInsertObjectsEvent;
21
use FOS\ElasticaBundle\Persister\Event\PostInsertObjectsEvent;
22
use FOS\ElasticaBundle\Persister\InPlacePagerPersister;
23
use FOS\ElasticaBundle\Persister\PagerPersisterInterface;
24
use FOS\ElasticaBundle\Persister\PagerPersisterRegistry;
25
use FOS\ElasticaBundle\Provider\PagerProviderRegistry;
26
use Symfony\Component\Console\Command\Command;
27
use Symfony\Component\Console\Helper\ProgressBar;
28
use Symfony\Component\Console\Helper\QuestionHelper;
29
use Symfony\Component\Console\Input\InputInterface;
30
use Symfony\Component\Console\Input\InputOption;
31
use Symfony\Component\Console\Output\OutputInterface;
32
use Symfony\Component\Console\Question\Question;
33
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
34
35
/**
36
 * Populate the search index.
37
 */
38
class PopulateCommand extends Command
39
{
40
    protected static $defaultName = 'fos:elastica:populate';
41
42
    /**
43
     * @var EventDispatcherInterface
44
     */
45
    private $dispatcher;
46
47
    /**
48
     * @var IndexManager
49
     */
50
    private $indexManager;
51
52
    /**
53
     * @var PagerProviderRegistry
54
     */
55
    private $pagerProviderRegistry;
56
57
    /**
58
     * @var PagerPersisterRegistry
59
     */
60
    private $pagerPersisterRegistry;
61
62
    /**
63
     * @var PagerPersisterInterface
64
     */
65
    private $pagerPersister;
66
67
    /**
68
     * @var Resetter
69
     */
70
    private $resetter;
71
72 4
    public function __construct(
73
        EventDispatcherInterface $dispatcher,
74
        IndexManager $indexManager,
75
        PagerProviderRegistry $pagerProviderRegistry,
76
        PagerPersisterRegistry $pagerPersisterRegistry,
77
        Resetter $resetter
78
    ) {
79 4
        parent::__construct();
80
81 4
        $this->dispatcher = $dispatcher;
82 4
        $this->indexManager = $indexManager;
83 4
        $this->pagerProviderRegistry = $pagerProviderRegistry;
84 4
        $this->pagerPersisterRegistry = $pagerPersisterRegistry;
85 4
        $this->resetter = $resetter;
86 4
    }
87
88 4
    protected function configure()
89
    {
90
        $this
91 4
            ->setName('fos:elastica:populate')
92 4
            ->addOption('index', null, InputOption::VALUE_OPTIONAL, 'The index to repopulate')
93 4
            ->addOption('no-reset', null, InputOption::VALUE_NONE, 'Do not reset index before populating')
94 4
            ->addOption('no-delete', null, InputOption::VALUE_NONE, 'Do not delete index after populate')
95 4
            ->addOption('sleep', null, InputOption::VALUE_REQUIRED, 'Sleep time between persisting iterations (microseconds)', 0)
96 4
            ->addOption('ignore-errors', null, InputOption::VALUE_NONE, 'Do not stop on errors')
97 4
            ->addOption('no-overwrite-format', null, InputOption::VALUE_NONE, 'Prevent this command from overwriting ProgressBar\'s formats')
98
99 4
            ->addOption('first-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page to start population from. Including the given page.', 1)
100 4
            ->addOption('last-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page to end population on. Including the given page.', null)
101 4
            ->addOption('max-per-page', null, InputOption::VALUE_REQUIRED, 'The pager\'s page size', 100)
102 4
            ->addOption('pager-persister', null, InputOption::VALUE_REQUIRED, 'The pager persister to be used to populate the index', InPlacePagerPersister::NAME)
103
104 4
            ->setDescription('Populates search indexes from providers')
105
        ;
106 4
    }
107
108
    protected function initialize(InputInterface $input, OutputInterface $output)
109
    {
110
        $this->pagerPersister = $this->pagerPersisterRegistry->getPagerPersister($input->getOption('pager-persister'));
111
112
        if (!$input->getOption('no-overwrite-format')) {
113
            ProgressBar::setFormatDefinition('normal', " %current%/%max% [%bar%] %percent:3s%%\n%message%");
114
            ProgressBar::setFormatDefinition('verbose', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%\n%message%");
115
            ProgressBar::setFormatDefinition('very_verbose', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%\n%message%");
116
            ProgressBar::setFormatDefinition('debug', " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%\n%message%");
117
        }
118
    }
119
120
    protected function execute(InputInterface $input, OutputInterface $output)
121
    {
122
        $indexes = (null !== $index = $input->getOption('index')) ? [$index] : \array_keys($this->indexManager->getAllIndexes());
123
        $reset = !$input->getOption('no-reset');
124
        $delete = !$input->getOption('no-delete');
125
126
        $options = [
127
            'delete' => $delete,
128
            'reset' => $reset,
129
            'ignore_errors' => $input->getOption('ignore-errors'),
130
            'sleep' => $input->getOption('sleep'),
131
            'first_page' => $input->getOption('first-page'),
132
            'max_per_page' => $input->getOption('max-per-page'),
133
        ];
134
135
        if ($input->getOption('last-page')) {
136
            $options['last_page'] = $input->getOption('last-page');
137
        }
138
139
        if ($input->isInteractive() && $reset && 1 < $options['first_page']) {
140
            /** @var QuestionHelper $dialog */
141
            $dialog = $this->getHelperSet()->get('question');
142
            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>'))) {
143
                return 1;
144
            }
145
        }
146
147
        foreach ($indexes as $index) {
148
            $this->populateIndex($output, $index, $reset, $options);
149
        }
150
151
        return 0;
152
    }
153
154
    /**
155
     * Recreates an index, populates it, and refreshes it.
156
     */
157
    private function populateIndex(OutputInterface $output, string $index, bool $reset, $options): void
158
    {
159
        $this->dispatcher->dispatch($event = new PreIndexPopulateEvent($index, $reset, $options));
0 ignored issues
show
Documentation introduced by
$event = new \FOS\Elasti...ndex, $reset, $options) is of type object<FOS\ElasticaBundl...\PreIndexPopulateEvent>, but the function expects a object<Symfony\Contracts\EventDispatcher\object>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
160
161
        if ($reset = $event->isReset()) {
162
            $output->writeln(\sprintf('<info>Resetting</info> <comment>%s</comment>', $index));
163
            $this->resetter->resetIndex($index, true);
164
        }
165
166
        $offset = 1 < $options['first_page'] ? ($options['first_page'] - 1) * $options['max_per_page'] : 0;
167
        $loggerClosure = ProgressClosureBuilder::build($output, 'Populating', $index, $offset);
168
169
        $this->dispatcher->addListener(
170
            OnExceptionEvent::class,
171
            function (OnExceptionEvent $event) use ($loggerClosure) {
172
                $loggerClosure(
173
                    \count($event->getObjects()),
174
                    $event->getPager()->getNbResults(),
175
                    \sprintf('<error>%s</error>', $event->getException()->getMessage())
176
                );
177
            }
178
        );
179
180
        $this->dispatcher->addListener(
181
            PostInsertObjectsEvent::class,
182
            function (PostInsertObjectsEvent $event) use ($loggerClosure) {
183
                $loggerClosure(\count($event->getObjects()), $event->getPager()->getNbResults());
184
            }
185
        );
186
187
        $this->dispatcher->addListener(
188
            PostAsyncInsertObjectsEvent::class,
189
            function (PostAsyncInsertObjectsEvent $event) use ($loggerClosure) {
190
                $loggerClosure($event->getObjectsCount(), $event->getPager()->getNbResults(), $event->getErrorMessage());
191
            }
192
        );
193
194
        if ($options['ignore_errors']) {
195
            $this->dispatcher->addListener(
196
                OnExceptionEvent::class,
197
                function (OnExceptionEvent $event) {
198
                    if ($event->getException() instanceof BulkResponseException) {
199
                        $event->setIgnored(true);
200
                    }
201
                }
202
            );
203
        }
204
205
        $provider = $this->pagerProviderRegistry->getProvider($index);
206
        $pager = $provider->provide($options);
207
208
        $this->pagerPersister->insert($pager, \array_merge($options, ['indexName' => $index]));
209
210
        $this->dispatcher->dispatch(new PostIndexPopulateEvent($index, $reset, $options));
0 ignored issues
show
Documentation introduced by
new \FOS\ElasticaBundle\...ndex, $reset, $options) is of type object<FOS\ElasticaBundl...PostIndexPopulateEvent>, but the function expects a object<Symfony\Contracts\EventDispatcher\object>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
211
212
        $this->refreshIndex($output, $index);
213
    }
214
215
    /**
216
     * Refreshes an index.
217
     */
218
    private function refreshIndex(OutputInterface $output, string $index): void
219
    {
220
        $output->writeln(\sprintf('<info>Refreshing</info> <comment>%s</comment>', $index));
221
        $this->indexManager->getIndex($index)->refresh();
222
        $output->writeln('');
223
    }
224
}
225