Completed
Push — main ( 1e072e...5ab8df )
by
unknown
16s queued 14s
created

UpdateIndexCommand::execute()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 22
c 1
b 0
f 1
nc 10
nop 2
dl 0
loc 38
rs 8.6346
1
<?php
2
declare(strict_types=1);
3
4
namespace BEdita\ElasticSearch\Command;
5
6
use BEdita\Core\Search\SearchRegistry;
7
use BEdita\ElasticSearch\Adapter\ElasticSearchAdapter;
8
use Cake\Command\Command;
9
use Cake\Console\Arguments;
10
use Cake\Console\ConsoleIo;
11
use Cake\Console\ConsoleOptionParser;
12
use Cake\Core\Configure;
13
14
/**
15
 * Utility command to update the configured ElasticSearch index.
16
 */
17
class UpdateIndexCommand extends Command
18
{
19
    /**
20
     * @inheritDoc
21
     */
22
    protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
23
    {
24
        return parent::buildOptionParser($parser)
25
            ->setDescription('Update ElasticSearch indices for configured adapters.')
26
            ->addOption('adapters', [
27
                'help' => 'Update indices only for these adapters (comma-separated list).',
28
                'required' => false,
29
            ]);
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     *
35
     * @throws \Exception Error loading adapter from registry
36
     */
37
    public function execute(Arguments $args, ConsoleIo $io): int|null
38
    {
39
        $registry = new SearchRegistry();
40
        $adapters = array_keys((array)Configure::read('Search.adapters'));
41
        if ($args->hasOption('adapters')) {
42
            $adapters = explode(',', (string)$args->getOption('adapters'));
43
        }
44
45
        foreach ($adapters as $name) {
46
            $config = (array)Configure::read(sprintf('Search.adapters.%s', $name));
47
            if (empty($config)) {
48
                $io->warning(sprintf('Missing configuration for adapter "%s", skipping index update', $name));
49
50
                continue;
51
            }
52
53
            $adapter = $registry->load($name, $config);
54
            if (!$adapter instanceof ElasticSearchAdapter) {
55
                $io->warning(sprintf(
56
                    'Adapter "%s" is not an instance of %s, skipping index update',
57
                    $name,
58
                    ElasticSearchAdapter::class,
59
                ));
60
61
                continue;
62
            }
63
64
            $index = $adapter->getIndex();
65
            if (!$index->updateProperties() || !$index->updateAnalysis()) {
66
                $io->error(sprintf('Error updating index "%s" for adapter "%s"', $index->getName(), $name));
67
68
                continue;
69
            }
70
71
            $io->success(sprintf('Updated index "%s" for adapter "%s"', $index->getName(), $name));
72
        }
73
74
        return static::CODE_SUCCESS;
75
    }
76
}
77