WordMatcher.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer;
  13. /**
  14. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  15. *
  16. * @internal
  17. */
  18. final class WordMatcher
  19. {
  20. /**
  21. * @var list<string>
  22. */
  23. private array $candidates;
  24. /**
  25. * @param list<string> $candidates
  26. */
  27. public function __construct(array $candidates)
  28. {
  29. $this->candidates = $candidates;
  30. }
  31. public function match(string $needle): ?string
  32. {
  33. $word = null;
  34. $distance = ceil(\strlen($needle) * 0.35);
  35. foreach ($this->candidates as $candidate) {
  36. $candidateDistance = levenshtein($needle, $candidate);
  37. if ($candidateDistance < $distance) {
  38. $word = $candidate;
  39. $distance = $candidateDistance;
  40. }
  41. }
  42. return $word;
  43. }
  44. }