diff --git a/Aggregation/CardinalityAggregation.php b/Aggregation/CardinalityAggregation.php index 36aec868229a697a497e5a7301d1700d70a957f6..fdcb0ee79ce5c41c6102734f9ca4f5e1d400ceec 100644 --- a/Aggregation/CardinalityAggregation.php +++ b/Aggregation/CardinalityAggregation.php @@ -12,6 +12,7 @@ namespace ONGR\ElasticsearchBundle\DSL\Aggregation; use ONGR\ElasticsearchBundle\DSL\Aggregation\Type\MetricTrait; +use ONGR\ElasticsearchBundle\DSL\ScriptAwareTrait; /** * Difference values counter. @@ -19,6 +20,7 @@ use ONGR\ElasticsearchBundle\DSL\Aggregation\Type\MetricTrait; class CardinalityAggregation extends AbstractAggregation { use MetricTrait; + use ScriptAwareTrait; /** * @var int @@ -30,33 +32,24 @@ class CardinalityAggregation extends AbstractAggregation */ private $rehash; - /** - * @var string - */ - private $script; - /** * {@inheritdoc} */ public function getArray() { - $out = []; - - if ($this->getField()) { - $out['field'] = $this->getField(); - } elseif ($this->getScript()) { - $out['script'] = $this->getScript(); - } else { - throw new \LogicException('Cardinality aggregation must have field or script set.'); - } - - if ($this->getPrecisionThreshold()) { - $out['precision_threshold'] = $this->getPrecisionThreshold(); - } - - if ($this->isRehash()) { - $out['rehash'] = $this->isRehash(); - } + $out = array_filter( + [ + 'field' => $this->getField(), + 'script' => $this->getScript(), + 'precision_threshold' => $this->getPrecisionThreshold(), + 'rehash' => $this->isRehash(), + ], + function ($val) { + return ($val || is_bool($val)); + } + ); + + $this->checkRequiredFields($out); return $out; } @@ -96,26 +89,24 @@ class CardinalityAggregation extends AbstractAggregation } /** - * @return string - */ - public function getScript() - { - return $this->script; - } - - /** - * @param string $script + * {@inheritdoc} */ - public function setScript($script) + public function getType() { - $this->script = $script; + return 'cardinality'; } /** - * {@inheritdoc} + * Checks if required fields are set. + * + * @param array $fields + * + * @throws \LogicException */ - public function getType() + private function checkRequiredFields($fields) { - return 'cardinality'; + if (!array_key_exists('field', $fields) && !array_key_exists('script', $fields)) { + throw new \LogicException('Cardinality aggregation must have field or script set.'); + } } }