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 * @phpstan-import-type TCreateQueryArgsMatching from BaseQuery
14 */
15class HasChild extends AbstractQuery
16{
17    /**
18     * @param AbstractQuery|array|BaseQuery|string|null $query
19     * @phpstan-param TCreateQueryArgsMatching $query
20     *
21     * @param string|null $type Parent document type
22     */
23    public function __construct($query, ?string $type = null)
24    {
25        $this->setType($type);
26        $this->setQuery($query);
27    }
28
29    /**
30     * Sets query object.
31     *
32     * @param AbstractQuery|array|BaseQuery|string|null $query
33     * @phpstan-param TCreateQueryArgsMatching $query
34     *
35     * @return $this
36     */
37    public function setQuery($query): self
38    {
39        return $this->setParam('query', BaseQuery::create($query));
40    }
41
42    /**
43     * Set type of the parent document.
44     *
45     * @param string|null $type Parent document type
46     *
47     * @return $this
48     */
49    public function setType(?string $type = null): self
50    {
51        return $this->setParam('type', $type);
52    }
53
54    /**
55     * Sets the scope.
56     *
57     * @param string $scope Scope
58     *
59     * @return $this
60     */
61    public function setScope(string $scope): self
62    {
63        return $this->setParam('_scope', $scope);
64    }
65
66    /**
67     * Set inner hits.
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