|
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
|
|
|
$config = (array)Configure::read(sprintf('Search.adapters.%s', $name)); |
|
47
|
|
|
if (empty($config)) { |
|
48
|
|
|
$io->warning(sprintf('Missing configuration for adapter "%s", skipping index creation', $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 creation', |
|
57
|
|
|
$name, |
|
58
|
|
|
ElasticSearchAdapter::class, |
|
59
|
|
|
)); |
|
60
|
|
|
|
|
61
|
|
|
continue; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
$index = $adapter->getIndex(); |
|
65
|
|
|
if (!$index->create()) { |
|
66
|
|
|
$io->error(sprintf('Error creating index "%s" for adapter "%s"', $index->getName(), $name)); |
|
67
|
|
|
|
|
68
|
|
|
continue; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$io->success(sprintf('Created index "%s" for adapter "%s"', $index->getName(), $name)); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return static::CODE_SUCCESS; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|