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 create the configured ElasticSearch index. |
16
|
|
|
*/ |
17
|
|
|
class CreateIndexCommand extends Command |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @inheritDoc |
21
|
|
|
*/ |
22
|
|
|
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser |
23
|
|
|
{ |
24
|
|
|
return parent::buildOptionParser($parser) |
25
|
|
|
->setDescription('Create ElasticSearch indices for configured adapters.') |
26
|
|
|
->addOption('adapters', [ |
27
|
|
|
'help' => 'Create 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
|
|
|
/** @var array<string, mixed> $config */ |
47
|
|
|
$config = (array)Configure::read(sprintf('Search.adapters.%s', $name)); |
48
|
|
|
if (empty($config)) { |
49
|
|
|
$io->warning(sprintf('Missing configuration for adapter "%s", skipping index creation', $name)); |
50
|
|
|
|
51
|
|
|
continue; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$adapter = $registry->load($name, $config); |
55
|
|
|
if (!$adapter instanceof ElasticSearchAdapter) { |
56
|
|
|
$io->warning(sprintf( |
57
|
|
|
'Adapter "%s" is not an instance of %s, skipping index creation', |
58
|
|
|
$name, |
59
|
|
|
ElasticSearchAdapter::class, |
60
|
|
|
)); |
61
|
|
|
|
62
|
|
|
continue; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$index = $adapter->getIndex(); |
66
|
|
|
if (!$index->create()) { |
67
|
|
|
$io->error(sprintf('Error creating index "%s" for adapter "%s"', $index->getName(), $name)); |
68
|
|
|
|
69
|
|
|
continue; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$io->success(sprintf('Created index "%s" for adapter "%s"', $index->getName(), $name)); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return static::CODE_SUCCESS; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|