1<?php
2
3namespace Elastica\Aggregation;
4
5use Elastica\Exception\InvalidException;
6
7abstract class AbstractSimpleAggregation extends AbstractAggregation
8{
9    /**
10     * Set the field for this aggregation.
11     *
12     * @param string $field the name of the document field on which to perform this aggregation
13     *
14     * @return $this
15     */
16    public function setField(string $field): self
17    {
18        return $this->setParam('field', $field);
19    }
20
21    /**
22     * Set a script for this aggregation.
23     *
24     * @param string|\Elastica\Script\AbstractScript $script
25     *
26     * @return $this
27     */
28    public function setScript($script): self
29    {
30        return $this->setParam('script', $script);
31    }
32
33    /**
34     * {@inheritdoc}
35     */
36    public function toArray(): array
37    {
38        if (!$this->hasParam('field') && !$this->hasParam('script')) {
39            throw new InvalidException(
40                'Either the field param or the script param should be set'
41            );
42        }
43        $array = parent::toArray();
44
45        $baseName = $this->_getBaseName();
46
47        if (isset($array[$baseName]['script']) && \is_array($array[$baseName]['script'])) {
48            $script = $array[$baseName]['script'];
49
50            unset($array[$baseName]['script']);
51
52            $array[$baseName] = \array_merge($array[$baseName], $script);
53        }
54
55        return $array;
56    }
57}
58