Skip to content

Instantly share code, notes, and snippets.

@chalasr
Last active July 19, 2016 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chalasr/b467ce946479fcf75292147cde2a1e23 to your computer and use it in GitHub Desktop.
Save chalasr/b467ce946479fcf75292147cde2a1e23 to your computer and use it in GitHub Desktop.
"Did you mean ...?" exception sample

Did you mean ...?

This function takes two main arguments that are $search and $possibleMatches and looks for a the closest word to $search in the $possibleMatches list.

Usage

$search = 'fio';
$possibleMatches = ['foo', 'bar', 'baz'];

if (!in_array($search, $possibleMatches)) {
    throw didYouMean($search, array_keys($possibleMatches));
}

// Output: Unable to find a value matching with "fio". Did you mean "foo"?
<?php
/**
* Throws a "Did you mean ...?" exception.
*
* @param string $search
* @param array $possibleMatches
*
* @return \LogicException
*/
function didYouMean($search, array $possibleMatches)
{
$minScore = INF;
foreach ($possibleMatches as $key) {
$distance = levenshtein($search, $key);
if ($distance < $minScore) {
$guess = $key;
$minScore = $distance;
}
}
$notFoundMessage = sprintf('Unable to find a value matching with "%s"', $search);
if (isset($guess) && $minScore < 3) {
return new \LogicException(
sprintf("%s\n\nDid you mean \"%s\"?\n\n", $notFoundMessage, $guess)
);
}
return new Exception(
sprintf(
"%s\n\nPossible values are:\n%s",
$notFoundMessage,
implode(PHP_EOL, array_map(function ($match) { return sprintf('- %s', $match); }, $possibleMatches))
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment