1<?php
2
3namespace Elastica\Query;
4
5use Elastica\Exception\InvalidException;
6
7/**
8 * Fuzzy query.
9 *
10 * @author Nicolas Ruflin <spam@ruflin.com>
11 *
12 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html
13 */
14class Fuzzy extends AbstractQuery
15{
16    /**
17     * Construct a fuzzy query.
18     *
19     * @param string $fieldName Field name
20     * @param string $value     String to search for
21     */
22    public function __construct(string $fieldName = null, string $value = null)
23    {
24        if (null !== $fieldName && null !== $value) {
25            $this->setField($fieldName, $value);
26        }
27    }
28
29    /**
30     * Set field for fuzzy query.
31     *
32     * @param string $fieldName Field name
33     * @param string $value     String to search for
34     *
35     * @return $this
36     */
37    public function setField(string $fieldName, string $value): self
38    {
39        if (!\is_string($value) || !\is_string($fieldName)) {
40            throw new InvalidException('The field and value arguments must be of type string.');
41        }
42        if (\count($this->getParams()) > 0 && \key($this->getParams()) !== $fieldName) {
43            throw new InvalidException('Fuzzy query can only support a single field.');
44        }
45
46        return $this->setParam($fieldName, ['value' => $value]);
47    }
48
49    /**
50     * Set optional parameters on the existing query.
51     *
52     * @param string $option option name
53     * @param mixed  $value  Value of the parameter
54     *
55     * @return $this
56     */
57    public function setFieldOption(string $option, $value): self
58    {
59        //Retrieve the single existing field for alteration.
60        $params = $this->getParams();
61        if (\count($params) < 1) {
62            throw new InvalidException('No field has been set');
63        }
64        $key = \key($params);
65        $params[$key][$option] = $value;
66
67        return $this->setParam($key, $params[$key]);
68    }
69}
70