1<?php
2
3namespace Elastica\Aggregation;
4
5/**
6 * Reversed Nested Aggregation.
7 *
8 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-reverse-nested-aggregation.html
9 */
10class ReverseNested extends AbstractAggregation
11{
12    /**
13     * @param string $name The name of this aggregation
14     * @param string $path Optional path to the nested object for this aggregation. Defaults to the root of the main document.
15     */
16    public function __construct(string $name, string $path = null)
17    {
18        parent::__construct($name);
19
20        if (null !== $path) {
21            $this->setPath($path);
22        }
23    }
24
25    /**
26     * Set the nested path for this aggregation.
27     *
28     * @param string $path
29     *
30     * @return $this
31     */
32    public function setPath(string $path)
33    {
34        return $this->setParam('path', $path);
35    }
36
37    /**
38     * {@inheritdoc}
39     */
40    public function toArray(): array
41    {
42        $array = parent::toArray();
43
44        // ensure we have an object for the reverse_nested key.
45        // if we don't have a path, then this would otherwise get encoded as an empty array, which is invalid.
46        $array['reverse_nested'] = (object) $array['reverse_nested'];
47
48        return $array;
49    }
50}
51