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 \Elastica\Script\AbstractScript|string $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('Either the field param or the script param should be set');
40        }
41        $array = parent::toArray();
42
43        $baseName = $this->_getBaseName();
44
45        if (isset($array[$baseName]['script']) && \is_array($array[$baseName]['script'])) {
46            $script = $array[$baseName]['script'];
47
48            unset($array[$baseName]['script']);
49
50            $array[$baseName] = \array_merge($array[$baseName], $script);
51        }
52
53        return $array;
54    }
55}
56