Skip to content
Snippets Groups Projects
IndexRunner.php 1.12 KiB
Newer Older
Pavel's avatar
Pavel committed
<?php

namespace IQDEV\ElasticSearch\Indexer;

use Elastic\Elasticsearch\Client;
use IQDEV\ElasticSearch\Configuration;

final class IndexRunner
{
    private Client $esClient;
    private Configuration $configuration;

    public function __construct(
        Client $esClient,
        Configuration $configuration
    ) {
        $this->esClient = $esClient;
        $this->configuration = $configuration;
    }

    public function run(IndexProvider $indexProvider)
    {
        if ($this->esClient->indices()->exists(['index' => $this->configuration->getIndexName()])->asBool() === false) {
            $this->esClient->indices()->create(
                [
                    'index' => $this->configuration->getIndexName(),
                    'body' => [
                        'mappings' => $this->configuration->getMapping(),
                    ],
                ]
            );
        }

        foreach ($indexProvider->get() as $index) {
            if (!$index instanceof Index) {
                continue;
            }
            $esIndex = $index->es();

            $this->esClient->index($esIndex);
        }
    }
}