devel_wizard-2.x-dev/src/Controller/AutocompleteConfigEntityInstanceController.php
src/Controller/AutocompleteConfigEntityInstanceController.php
<?php
declare(strict_types=1);
namespace Drupal\devel_wizard\Controller;
use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class AutocompleteConfigEntityInstanceController extends ControllerBase {
protected int $minKeywordLength = 2;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
);
}
public function __construct(EntityTypeManagerInterface $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
}
public function body(Request $request, string $entityTypeId) {
$etm = $this->entityTypeManager();
$matches = [];
$keyword = mb_strtolower($request->query->get('q', ''));
if (mb_strlen($keyword) < $this->minKeywordLength
|| !$etm->hasDefinition($entityTypeId)
) {
return new JsonResponse($matches);
}
/* @noinspection PhpUnhandledExceptionInspection */
$entityType = $etm->getDefinition($entityTypeId);
if (!($entityType instanceof ConfigEntityTypeInterface)) {
return new JsonResponse($matches);
}
/* @noinspection PhpUnhandledExceptionInspection */
$entities = $etm
->getStorage($entityTypeId)
->loadMultiple();
foreach ($entities as $entity) {
if (str_contains(mb_strtolower($entity->id()), $keyword)
|| str_contains(mb_strtolower($entity->label()), $keyword)
) {
$matches[] = [
'value' => $entity->id(),
'label' => $entity->label() . ' (' . $entity->id() . ')',
];
}
}
return new JsonResponse($matches);
}
}
