From 6ad5ac0879fa2be6fb939b0121b56a670384a1a3 Mon Sep 17 00:00:00 2001
From: Aivaras Gotovskis <aivaras.gotovskis@ongr.io>
Date: Thu, 9 Jul 2015 16:00:34 +0300
Subject: [PATCH] Add constructor arguments to RangeAggregation.

---
 src/Aggregation/RangeAggregation.php       | 22 +++++++++++++++++++
 tests/Aggregation/RangeAggregationTest.php | 25 ++++++++++++++++++++++
 2 files changed, 47 insertions(+)

diff --git a/src/Aggregation/RangeAggregation.php b/src/Aggregation/RangeAggregation.php
index 41e1075..557e9c4 100644
--- a/src/Aggregation/RangeAggregation.php
+++ b/src/Aggregation/RangeAggregation.php
@@ -30,6 +30,28 @@ class RangeAggregation extends AbstractAggregation
      */
     private $keyed = false;
 
+    /**
+     * Inner aggregations container init.
+     *
+     * @param string $name
+     * @param string $field
+     * @param array  $ranges
+     * @param bool   $keyed
+     */
+    public function __construct($name, $field = null, $ranges = [], $keyed = false)
+    {
+        parent::__construct($name);
+
+        $this->setField($field);
+        $this->setKeyed($keyed);
+        foreach ($ranges as $range) {
+            $from = isset($range['from']) ? $range['from'] : null;
+            $to = isset($range['to']) ? $range['to'] : null;
+            $key = isset($range['key']) ? $range['key'] : null;
+            $this->addRange($from, $to, $key);
+        }
+    }
+
     /**
      * Sets if result buckets should be keyed.
      *
diff --git a/tests/Aggregation/RangeAggregationTest.php b/tests/Aggregation/RangeAggregationTest.php
index 9414ea5..c66244d 100644
--- a/tests/Aggregation/RangeAggregationTest.php
+++ b/tests/Aggregation/RangeAggregationTest.php
@@ -199,4 +199,29 @@ class RangeAggregationTest extends \PHPUnit_Framework_TestCase
         $result = $aggregation->removeRange(500, 700);
         $this->assertFalse($result, 'returns false after removing not-existing range');
     }
+
+    /**
+     * Tests if parameter can be passed to constructor.
+     */
+    public function testConstructor()
+    {
+        $aggregation = new RangeAggregation('foo', 'fieldValue', [['from' => 'now', 'key' => 'nowkey']], true);
+        $this->assertSame(
+            [
+                'agg_foo' => [
+                    'range' => [
+                        'keyed' => true,
+                        'ranges' => [
+                            [
+                                'from' => 'now',
+                                'key' => 'nowkey',
+                            ],
+                        ],
+                        'field' => 'fieldValue',
+                    ],
+                ],
+            ],
+            $aggregation->toArray()
+        );
+    }
 }
-- 
GitLab