1<?php
2
3namespace Elastica\Query;
4
5use Elastica\Query as BaseQuery;
6
7/**
8 * Returns parent documents having child docs matching the query.
9 *
10 * @author Fabian Vogler <fabian@equivalence.ch>
11 *
12 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-has-child-query.html
13 */
14class HasChild extends AbstractQuery
15{
16    /**
17     * Construct HasChild Query.
18     *
19     * @param string|BaseQuery|AbstractQuery $query
20     * @param string                         $type  Parent document type
21     */
22    public function __construct($query, string $type = null)
23    {
24        $this->setType($type);
25        $this->setQuery($query);
26    }
27
28    /**
29     * Sets query object.
30     *
31     * @param string|BaseQuery|AbstractQuery $query
32     *
33     * @return $this
34     */
35    public function setQuery($query): self
36    {
37        return $this->setParam('query', BaseQuery::create($query));
38    }
39
40    /**
41     * Set type of the parent document.
42     *
43     * @param string $type Parent document type
44     *
45     * @return $this
46     */
47    public function setType(string $type = null): self
48    {
49        return $this->setParam('type', $type);
50    }
51
52    /**
53     * Sets the scope.
54     *
55     * @param string $scope Scope
56     *
57     * @return $this
58     */
59    public function setScope(string $scope): self
60    {
61        return $this->setParam('_scope', $scope);
62    }
63
64    /**
65     * Set inner hits.
66     *
67     * @param InnerHits $innerHits
68     *
69     * @return $this
70     */
71    public function setInnerHits(InnerHits $innerHits): self
72    {
73        return $this->setParam('inner_hits', $innerHits);
74    }
75
76    /**
77     * {@inheritdoc}
78     */
79    public function toArray(): array
80    {
81        $array = parent::toArray();
82
83        $baseName = $this->_getBaseName();
84
85        if (isset($array[$baseName]['query'])) {
86            $array[$baseName]['query'] = $array[$baseName]['query']['query'];
87        }
88
89        return $array;
90    }
91}
92