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|null $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     * @return $this
29     */
30    public function setPath(string $path): self
31    {
32        return $this->setParam('path', $path);
33    }
34
35    /**
36     * {@inheritdoc}
37     */
38    public function toArray(): array
39    {
40        $array = parent::toArray();
41
42        // ensure we have an object for the reverse_nested key.
43        // if we don't have a path, then this would otherwise get encoded as an empty array, which is invalid.
44        $array['reverse_nested'] = (object) $array['reverse_nested'];
45
46        return $array;
47    }
48}
49