WP_CLI\Utils

get_suggestion()WP-CLI 1.0

Get the closest suggestion for a mis-typed target term amongst a list of options.

Uses the Levenshtein algorithm to calculate the relative "distance" between terms.

If the "distance" to the closest term is higher than the threshold, an empty string is returned.

Хуков нет.

Возвращает

Строку.

Использование

get_suggestion( $target, $options, $threshold );
$target(строка) (обязательный)
Target term to get a suggestion for.
$options(массив) (обязательный)
Array with possible options.
$threshold(int)
Threshold above which to return an empty string.
По умолчанию: 2

Код get_suggestion() WP-CLI 2.8.0-alpha

function get_suggestion( $target, array $options, $threshold = 2 ) {

	$suggestion_map = [
		'add'        => 'create',
		'check'      => 'check-update',
		'capability' => 'cap',
		'clear'      => 'flush',
		'decrement'  => 'decr',
		'del'        => 'delete',
		'directory'  => 'dir',
		'exec'       => 'eval',
		'exec-file'  => 'eval-file',
		'increment'  => 'incr',
		'language'   => 'locale',
		'lang'       => 'locale',
		'new'        => 'create',
		'number'     => 'count',
		'remove'     => 'delete',
		'regen'      => 'regenerate',
		'rep'        => 'replace',
		'repl'       => 'replace',
		'trash'      => 'delete',
		'v'          => 'version',
	];

	if ( array_key_exists( $target, $suggestion_map ) && in_array( $suggestion_map[ $target ], $options, true ) ) {
		return $suggestion_map[ $target ];
	}

	if ( empty( $options ) ) {
		return '';
	}
	foreach ( $options as $option ) {
		$distance               = levenshtein( $option, $target );
		$levenshtein[ $option ] = $distance;
	}

	// Sort known command strings by distance to user entry.
	asort( $levenshtein );

	// Fetch the closest command string.
	reset( $levenshtein );
	$suggestion = key( $levenshtein );

	// Only return a suggestion if below a given threshold.
	return $levenshtein[ $suggestion ] <= $threshold && $suggestion !== $target
		? (string) $suggestion
		: '';
}