Skip to content
Snippets Groups Projects
BaseIndexProvider.php 1.38 KiB
Newer Older
<?php

namespace IQDEV\ElasticSearch\Indexer;

use IQDEV\ElasticSearch\Configuration;
use IQDEV\ElasticSearch\Document\ProductDocument;
use IQDEV\ElasticSearch\Facet\FacetCategory;
use IQDEV\ElasticSearch\Facet\FacetKeyword;
use IQDEV\ElasticSearch\Facet\FacetNumber;

class BaseIndexProvider implements IndexProvider
{
    private array $products;
    private Configuration $configuration;

    public function __construct($products, $configuration)
    {
        $this->configuration = $configuration;
        $this->products = $products;
    }

    public function get(): \Generator
    {
        foreach ($this->products as $product) {
            $document = new ProductDocument(new FacetCategory($product['category']), $product['data'] ?? []);
            foreach ($product['properties'] as $type => $values) {
                foreach ($values as $key => $prop) {
                    if ($type === 'number') {
                        $document->getNumberFacets()->add(new FacetNumber($key, $prop));
                    } else {
                        $document->getKeywordFacets()->add(new FacetKeyword($key, $prop));
                    }
                }
            }
            $document->setFullSearchContent($product['name']);

            yield new Index(
                $this->configuration->getIndexName(),
                $document,
                $product['id']
            );
        }
    }
}