devel_wizard-2.x-dev/src/Controller/AutocompleteLibraryController.php
src/Controller/AutocompleteLibraryController.php
<?php
declare(strict_types=1);
namespace Drupal\devel_wizard\Controller;
use Drupal\Core\Asset\LibraryDiscoveryInterface;
use Drupal\Core\Extension\ExtensionList;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AutocompleteLibraryController extends AutocompleteBase {
protected ExtensionList $moduleList;
protected ExtensionList $profileList;
protected ExtensionList $themeList;
protected LibraryDiscoveryInterface $libraryDiscovery;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('extension.list.module'),
$container->get('extension.list.profile'),
$container->get('extension.list.theme'),
$container->get('library.discovery'),
);
}
public function __construct(
ExtensionList $moduleList,
ExtensionList $profileList,
ExtensionList $themeList,
LibraryDiscoveryInterface $libraryDiscovery,
) {
$this->moduleList = $moduleList;
$this->profileList = $profileList;
$this->themeList = $themeList;
$this->libraryDiscovery = $libraryDiscovery;
}
protected function getFuzzyOptions(): array {
$options = parent::getFuzzyOptions();
$options['keys'][] = 'extension';
$options['keys'][] = 'name';
$options['keys'][] = 'files';
return $options;
}
protected function getFuzzyDocuments(string $keyword): array {
$documents = [];
/** @var \Drupal\Core\Extension\ExtensionList $list */
foreach ([$this->moduleList, $this->profileList, $this->themeList] as $list) {
foreach (array_keys($list->getList()) as $extensionName) {
foreach ($this->libraryDiscovery->getLibrariesByExtension($extensionName) as $libraryName => $library) {
$documents[] = $this->convertEntryToFuzzyDocument([
'extensionName' => $extensionName,
'libraryName' => $libraryName,
'library' => $library,
]);
}
}
}
return $documents;
}
protected function convertEntryToFuzzyDocument(array $entry): array {
$doc = [
'extension' => $entry['extensionName'],
'name' => $entry['libraryName'],
'files' => [],
];
foreach ($entry['library']['css'] ?? [] as $file) {
$doc['files'][] = $file['data'];
}
foreach ($entry['library']['js'] ?? [] as $file) {
$doc['files'][] = $file['data'];
}
return $doc;
}
protected function convertFuzzyResultToAutocompleteItem(array $result): array {
return [
'value' => "{$result['item']['extension']}/{$result['item']['name']}",
'label' => "{$result['item']['extension']}/{$result['item']['name']}",
];
}
}
