function CompletionTrait::suggestAvailablePackage
Suggest package names available on all configured repositories.
File
-
vendor/
composer/ composer/ src/ Composer/ Command/ CompletionTrait.php, line 153
Class
- CompletionTrait
- Adds completion to arguments and options.
Namespace
Composer\CommandCode
private function suggestAvailablePackage(int $max = 99) : \Closure {
return function (CompletionInput $input) use ($max) : array {
if ($max < 1) {
return [];
}
$composer = $this->requireComposer();
$repos = new CompositeRepository($composer->getRepositoryManager()
->getRepositories());
$results = [];
$showVendors = false;
if (!str_contains($input->getCompletionValue(), '/')) {
$results = $repos->search('^' . preg_quote($input->getCompletionValue()), RepositoryInterface::SEARCH_VENDOR);
$showVendors = true;
}
// if we get a single vendor, we expand it into its contents already
if (\count($results) <= 1) {
$results = $repos->search('^' . preg_quote($input->getCompletionValue()), RepositoryInterface::SEARCH_NAME);
$showVendors = false;
}
$results = array_column($results, 'name');
if ($showVendors) {
$results = array_map(static function (string $name) : string {
return $name . '/';
}, $results);
// sort shorter results first to avoid auto-expanding the completion to a longer string than needed
usort($results, static function (string $a, string $b) {
$lenA = \strlen($a);
$lenB = \strlen($b);
if ($lenA === $lenB) {
return $a <=> $b;
}
return $lenA - $lenB;
});
$pinned = [];
// ensure if the input is an exact match that it is always in the result set
$completionInput = $input->getCompletionValue() . '/';
if (false !== ($exactIndex = array_search($completionInput, $results, true))) {
$pinned[] = $completionInput;
array_splice($results, $exactIndex, 1);
}
return array_merge($pinned, array_slice($results, 0, $max - \count($pinned)));
}
return array_slice($results, 0, $max);
};
}