Fuzzy.php 1.8 KB

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