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

namespace IQDEV\ElasticSearch\Search\Aggs;

use IQDEV\ElasticSearch\Esable;
use IQDEV\ElasticSearch\Search\BoolQuery\Query;
use IQDEV\ElasticSearch\Search\Nested;

final class Aggs implements Esable
{
    private ?AggsCollection $aggs = null;
    private ?Query $query = null;
    private ?Nested $nested = null;
    private ?Terms $terms = null;
Pavel's avatar
Pavel committed
    private ?Stats $stats = null;
Pavel's avatar
Pavel committed

    public function __construct(
        private string $key
    ) {
Pavel's avatar
Pavel committed
    }

Pavel's avatar
Pavel committed
    public function addAggs(Aggs $aggs): self
Pavel's avatar
Pavel committed
    {
Pavel's avatar
Pavel committed
        if (null === $this->aggs) {
Pavel's avatar
Pavel committed
            $this->aggs = new AggsCollection();
        }

        $this->aggs->add($aggs);
Pavel's avatar
Pavel committed
        return $this;
    }

    public function setQuery(?Query $query): self
    {
        $this->query = $query;
Pavel's avatar
Pavel committed
        return $this;
    }

    public function setNested(?Nested $nested): self
    {
        $this->nested = $nested;
Pavel's avatar
Pavel committed
        return $this;
    }

    public function setTerms(?Terms $terms): self
    {
        $this->terms = $terms;
Pavel's avatar
Pavel committed
        return $this;
    }

Pavel's avatar
Pavel committed
    public function setStats(?Stats $stats): self
Pavel's avatar
Pavel committed
    {
Pavel's avatar
Pavel committed
        $this->stats = $stats;

Pavel's avatar
Pavel committed
        return $this;
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function es(): array
    {
        $agg = [];

        if ($this->aggs) {
            $agg['aggs'] = array_merge($agg, $this->aggs->es()['aggs']);
        }

Pavel's avatar
Pavel committed
        if ($this->query && false === $this->query->isEmpty()) {
Pavel's avatar
Pavel committed
            $agg['filter'] = $this->query->es()[$this->query->getType()];
        }

        if ($this->nested) {
            $agg['nested'] = $this->nested->es()['nested'];
        }

        if ($this->terms) {
            $agg['terms'] = $this->terms->es()['terms'];
        }
Pavel's avatar
Pavel committed

        if ($this->stats) {
            $agg['stats'] = $this->stats->es()['stats'];
Pavel's avatar
Pavel committed
        }

        return $agg;
    }
Pavel's avatar
Pavel committed
}