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 implements GapPolicyInterface
13{
14    use Traits\GapPolicyTrait;
15
16    public function __construct(string $name, ?array $bucketsPath = null, ?string $script = null)
17    {
18        parent::__construct($name);
19
20        if (null !== $bucketsPath) {
21            $this->setBucketsPath($bucketsPath);
22        } elseif (\func_num_args() >= 2) {
23            \trigger_deprecation('ruflin/elastica', '7.4.0', 'Passing null as 2nd argument to "%s()" is deprecated, pass an array instead. It will be mandatory in 8.0.', __METHOD__);
24        } else {
25            \trigger_deprecation('ruflin/elastica', '7.4.0', 'Not passing a 2nd argument to "%s()" is deprecated, pass an array instead. It will be mandatory in 8.0.', __METHOD__);
26        }
27
28        if (null !== $script) {
29            $this->setScript($script);
30        } elseif (\func_num_args() >= 3) {
31            \trigger_deprecation('ruflin/elastica', '7.4.0', 'Passing null as 3rd argument to "%s()" is deprecated, pass a string instead. It will be mandatory in 8.0.', __METHOD__);
32        } else {
33            \trigger_deprecation('ruflin/elastica', '7.4.0', 'Not passing a 3rd argument to "%s()" is deprecated, pass a string instead. It will be mandatory in 8.0.', __METHOD__);
34        }
35    }
36
37    /**
38     * Set the buckets_path for this aggregation.
39     *
40     * @return $this
41     */
42    public function setBucketsPath(array $bucketsPath): self
43    {
44        return $this->setParam('buckets_path', $bucketsPath);
45    }
46
47    /**
48     * Set the script for this aggregation.
49     *
50     * @return $this
51     */
52    public function setScript(string $script): self
53    {
54        return $this->setParam('script', $script);
55    }
56
57    /**
58     * Set the format for this aggregation.
59     *
60     * @return $this
61     */
62    public function setFormat(?string $format = null): self
63    {
64        return $this->setParam('format', $format);
65    }
66
67    /**
68     * @throws InvalidException If buckets path or script is not set
69     */
70    public function toArray(): array
71    {
72        if (!$this->hasParam('buckets_path')) {
73            throw new InvalidException('Buckets path is required');
74        }
75        if (!$this->hasParam('script')) {
76            throw new InvalidException('Script parameter is required');
77        }
78
79        return parent::toArray();
80    }
81}
82