CategoryAutocompleteController.php in Drupal 9
File
core/modules/block/src/Controller/CategoryAutocompleteController.php
View source
<?php
namespace Drupal\block\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class CategoryAutocompleteController implements ContainerInjectionInterface {
protected $blockManager;
public function __construct(BlockManagerInterface $block_manager) {
$this->blockManager = $block_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.block'));
}
public function autocomplete(Request $request) {
$typed_category = $request->query
->get('q');
$matches = [];
foreach ($this->blockManager
->getCategories() as $category) {
if (stripos($category, $typed_category) === 0) {
$matches[] = [
'value' => $category,
'label' => Html::escape($category),
];
}
}
return new JsonResponse($matches);
}
}