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|null $value String to search for 20 */ 21 public function __construct(?string $fieldName = null, ?string $value = null) 22 { 23 if (null !== $fieldName && null !== $value) { 24 $this->setField($fieldName, $value); 25 } 26 } 27 28 /** 29 * Set field for fuzzy query. 30 * 31 * @param string $value String to search for 32 * 33 * @return $this 34 */ 35 public function setField(string $fieldName, string $value): self 36 { 37 if (\count($this->getParams()) > 0 && \key($this->getParams()) !== $fieldName) { 38 throw new InvalidException('Fuzzy query can only support a single field.'); 39 } 40 41 return $this->setParam($fieldName, ['value' => $value]); 42 } 43 44 /** 45 * Set optional parameters on the existing query. 46 * 47 * @param mixed $value Value of the parameter 48 * 49 * @return $this 50 */ 51 public function setFieldOption(string $option, $value): self 52 { 53 // Retrieve the single existing field for alteration. 54 $params = $this->getParams(); 55 if (\count($params) < 1) { 56 throw new InvalidException('No field has been set'); 57 } 58 $key = \key($params); 59 $params[$key][$option] = $value; 60 61 return $this->setParam($key, $params[$key]); 62 } 63} 64