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    public function __construct(?AbstractSuggest $suggestion = null)
16    {
17        if (null !== $suggestion) {
18            $this->addSuggestion($suggestion);
19        }
20    }
21
22    /**
23     * Set the global text for this suggester.
24     */
25    public function setGlobalText(string $text): self
26    {
27        return $this->setParam('text', $text);
28    }
29
30    /**
31     * Add a suggestion to this suggest clause.
32     */
33    public function addSuggestion(AbstractSuggest $suggestion): self
34    {
35        return $this->addParam('suggestion', $suggestion);
36    }
37
38    /**
39     * @param AbstractSuggest|Suggest $suggestion
40     *
41     * @throws Exception\NotImplementedException
42     */
43    public static function create($suggestion): self
44    {
45        switch (true) {
46            case $suggestion instanceof self:
47                return $suggestion;
48            case $suggestion instanceof AbstractSuggest:
49                return new static($suggestion);
50        }
51        throw new NotImplementedException();
52    }
53
54    /**
55     * {@inheritdoc}
56     */
57    public function toArray(): array
58    {
59        $array = parent::toArray();
60
61        $baseName = $this->_getBaseName();
62
63        if (isset($array[$baseName]['suggestion'])) {
64            $suggestion = $array[$baseName]['suggestion'];
65            unset($array[$baseName]['suggestion']);
66
67            foreach ($suggestion as $key => $value) {
68                $array[$baseName][$key] = $value;
69            }
70        }
71
72        return $array;
73    }
74}
75