PropertyAggregation.php 1.8 KiB
Newer Older
Pavel's avatar
Pavel committed
<?php

declare(strict_types=1);

namespace IQDEV\ElasticSearch\Converter\Request\Aggregation;

use IQDEV\ElasticSearch\Configuration;
use IQDEV\ElasticSearch\Converter\Request\FilterQuery;
use IQDEV\ElasticSearch\Criteria\Filter\Collection\FilterCollection;
use IQDEV\ElasticSearch\Document\Property\PropertyType;
use IQDEV\ElasticSearch\Search\Aggs\Aggs;
use IQDEV\ElasticSearch\Search\Aggs\AggsCollection;
use IQDEV\ElasticSearch\Search\Aggs\Terms;

class PropertyAggregation
{
    public function __construct(
        private readonly Configuration $configuration,
        private readonly FilterCollection $filterCollection,
        private readonly \IQDEV\ElasticSearch\Criteria\Aggs\AggsCollection $aggsCollection,
    ) {
    }

    public function updateRequestAggregation(AggsCollection $original): void
    {
        $queryFilterBuilder = new FilterQuery($this->configuration, $this->filterCollection);
        $query = $queryFilterBuilder->getQuery();

        /** @var \IQDEV\ElasticSearch\Criteria\Aggs\Aggs $aggs */
        foreach ($this->aggsCollection as $aggs) {
            $property = $aggs->getProperty();

            if ($property->getType() !== PropertyType::BASE) {
                continue;
            }

            $aggs = new Aggs($property->getKey());
            if (false === $query->isEmpty()) {
                $aggs->setQuery($query);
                $aggs->addAggs(
                    (new Aggs($property->getKey()))
                    ->setTerms(new Terms($property->getKey()))
                );
            } else {
                $aggs->setTerms(new Terms($property->getKey()));
            }
            $aggs->addAggs(
                (new Aggs($property->getKey()))
                    ->setTerms(new Terms($property->getKey()))
            );

            $original->add($aggs);
        }
    }
}