From 0a15ccd4941044c95e3d1338cd8485287649836c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mantas=20Jonu=C5=A1as?= <mantas.jonusas@nfq.lt> Date: Tue, 14 Apr 2015 10:58:25 +0300 Subject: [PATCH] Refactored cardinality aggregation --- Aggregation/CardinalityAggregation.php | 63 +++++++++++--------------- 1 file changed, 27 insertions(+), 36 deletions(-) diff --git a/Aggregation/CardinalityAggregation.php b/Aggregation/CardinalityAggregation.php index 36aec86..fdcb0ee 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.'); + } } } -- GitLab