1<?php
2
3namespace Elastica;
4
5use Elastica\Exception\QueryBuilderException;
6use Elastica\QueryBuilder\DSL;
7use Elastica\QueryBuilder\Facade;
8use Elastica\QueryBuilder\Version;
9
10/**
11 * Query Builder.
12 *
13 * @author Manuel Andreo Garcia <andreo.garcia@googlemail.com>
14 */
15class QueryBuilder
16{
17    /**
18     * @var Version
19     */
20    private $_version;
21
22    /**
23     * @var Facade[]
24     */
25    private $_facades = [];
26
27    /**
28     * Constructor.
29     *
30     * @param Version $version
31     */
32    public function __construct(Version $version = null)
33    {
34        $this->_version = $version ?: new Version\Latest();
35
36        $this->addDSL(new DSL\Query());
37        $this->addDSL(new DSL\Aggregation());
38        $this->addDSL(new DSL\Suggest());
39    }
40
41    /**
42     * Returns Facade for custom DSL object.
43     *
44     * @param $dsl
45     * @param array $arguments
46     *
47     * @throws QueryBuilderException
48     *
49     * @return Facade
50     */
51    public function __call($dsl, array $arguments)
52    {
53        if (false === isset($this->_facades[$dsl])) {
54            throw new QueryBuilderException('DSL "'.$dsl.'" not supported');
55        }
56
57        return $this->_facades[$dsl];
58    }
59
60    /**
61     * Adds a new DSL object.
62     *
63     * @param DSL $dsl
64     */
65    public function addDSL(DSL $dsl)
66    {
67        $this->_facades[$dsl->getType()] = new Facade($dsl, $this->_version);
68    }
69
70    /*
71     * convenience methods
72     */
73
74    /**
75     * Query DSL.
76     *
77     * @return DSL\Query
78     */
79    public function query()
80    {
81        return $this->_facades[DSL::TYPE_QUERY];
82    }
83
84    /**
85     * Aggregation DSL.
86     *
87     * @return DSL\Aggregation
88     */
89    public function aggregation()
90    {
91        return $this->_facades[DSL::TYPE_AGGREGATION];
92    }
93
94    /**
95     * Suggest DSL.
96     *
97     * @return DSL\Suggest
98     */
99    public function suggest()
100    {
101        return $this->_facades[DSL::TYPE_SUGGEST];
102    }
103}
104