1<?php
2
3namespace Elastica\Aggregation;
4
5use Elastica\Exception\InvalidException;
6
7/**
8 * Class BucketScript.
9 *
10 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html
11 */
12class BucketScript extends AbstractAggregation
13{
14    /**
15     * @param string      $name
16     * @param array|null  $bucketsPath
17     * @param string|null $script
18     */
19    public function __construct(string $name, array $bucketsPath = null, string $script = null)
20    {
21        parent::__construct($name);
22
23        if (null !== $bucketsPath) {
24            $this->setBucketsPath($bucketsPath);
25        }
26
27        if (null !== $script) {
28            $this->setScript($script);
29        }
30    }
31
32    /**
33     * Set the buckets_path for this aggregation.
34     *
35     * @param array $bucketsPath
36     *
37     * @return $this
38     */
39    public function setBucketsPath(array $bucketsPath): self
40    {
41        return $this->setParam('buckets_path', $bucketsPath);
42    }
43
44    /**
45     * Set the script for this aggregation.
46     *
47     * @param string $script
48     *
49     * @return $this
50     */
51    public function setScript(string $script): self
52    {
53        return $this->setParam('script', $script);
54    }
55
56    /**
57     * Set the gap policy for this aggregation.
58     *
59     * @param string $gapPolicy
60     *
61     * @return $this
62     */
63    public function setGapPolicy(string $gapPolicy = 'skip'): self
64    {
65        return $this->setParam('gap_policy', $gapPolicy);
66    }
67
68    /**
69     * Set the format for this aggregation.
70     *
71     * @param string|null $format
72     *
73     * @return $this
74     */
75    public function setFormat(string $format = null): self
76    {
77        return $this->setParam('format', $format);
78    }
79
80    /**
81     * @throws InvalidException If buckets path or script is not set
82     *
83     * @return array
84     */
85    public function toArray(): array
86    {
87        if (!$this->hasParam('buckets_path')) {
88            throw new InvalidException('Buckets path is required');
89        } elseif (!$this->hasParam('script')) {
90            throw new InvalidException('Script parameter is required');
91        }
92
93        return parent::toArray();
94    }
95}
96