3 namespace Drupal\block\Controller;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Block\BlockManagerInterface;
7 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9 use Symfony\Component\HttpFoundation\JsonResponse;
10 use Symfony\Component\HttpFoundation\Request;
13 * Returns autocomplete responses for block categories.
15 class CategoryAutocompleteController implements ContainerInjectionInterface {
20 * @var \Drupal\Core\Block\BlockManagerInterface
22 protected $blockManager;
25 * Constructs a new CategoryAutocompleteController.
27 * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
30 public function __construct(BlockManagerInterface $block_manager) {
31 $this->blockManager = $block_manager;
37 public static function create(ContainerInterface $container) {
39 $container->get('plugin.manager.block')
44 * Retrieves suggestions for block category autocompletion.
46 * @param \Symfony\Component\HttpFoundation\Request $request
47 * The current request.
49 * @return \Symfony\Component\HttpFoundation\JsonResponse
50 * A JSON response containing autocomplete suggestions.
52 public function autocomplete(Request $request) {
53 $typed_category = $request->query->get('q');
55 foreach ($this->blockManager->getCategories() as $category) {
56 if (stripos($category, $typed_category) === 0) {
57 $matches[] = ['value' => $category, 'label' => Html::escape($category)];
60 return new JsonResponse($matches);