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