1<?php
2
3namespace Elastica;
4
5use Elastica\Exception\NotImplementedException;
6use Elastica\Suggest\AbstractSuggest;
7
8/**
9 * Class Suggest.
10 *
11 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
12 */
13class Suggest extends Param
14{
15    /**
16     * @param AbstractSuggest $suggestion
17     */
18    public function __construct(AbstractSuggest $suggestion = null)
19    {
20        if (!\is_null($suggestion)) {
21            $this->addSuggestion($suggestion);
22        }
23    }
24
25    /**
26     * Set the global text for this suggester.
27     *
28     * @param string $text
29     *
30     * @return $this
31     */
32    public function setGlobalText($text)
33    {
34        return $this->setParam('text', $text);
35    }
36
37    /**
38     * Add a suggestion to this suggest clause.
39     *
40     * @param AbstractSuggest $suggestion
41     *
42     * @return $this
43     */
44    public function addSuggestion(AbstractSuggest $suggestion)
45    {
46        return $this->addParam('suggestion', $suggestion);
47    }
48
49    /**
50     * @param Suggest|AbstractSuggest $suggestion
51     *
52     * @throws Exception\NotImplementedException
53     *
54     * @return self
55     */
56    public static function create($suggestion)
57    {
58        switch (true) {
59            case $suggestion instanceof self:
60                return $suggestion;
61            case $suggestion instanceof AbstractSuggest:
62                return new self($suggestion);
63        }
64        throw new NotImplementedException();
65    }
66
67    /**
68     * {@inheritdoc}
69     */
70    public function toArray()
71    {
72        $array = parent::toArray();
73
74        $baseName = $this->_getBaseName();
75
76        if (isset($array[$baseName]['suggestion'])) {
77            $suggestion = $array[$baseName]['suggestion'];
78            unset($array[$baseName]['suggestion']);
79
80            foreach ($suggestion as $key => $value) {
81                $array[$baseName][$key] = $value;
82            }
83        }
84
85        return $array;
86    }
87}
88