c95fd477e82504bc3e5865de8cb724a1ccb728ad
[yaffs-website] / CategoryAutocompleteController.php
1 <?php
2
3 namespace Drupal\block\Controller;
4
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;
11
12 /**
13  * Returns autocomplete responses for block categories.
14  */
15 class CategoryAutocompleteController implements ContainerInjectionInterface {
16
17   /**
18    * The block manager.
19    *
20    * @var \Drupal\Core\Block\BlockManagerInterface
21    */
22   protected $blockManager;
23
24   /**
25    * Constructs a new CategoryAutocompleteController.
26    *
27    * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
28    *   The block manager.
29    */
30   public function __construct(BlockManagerInterface $block_manager) {
31     $this->blockManager = $block_manager;
32   }
33
34   /**
35    * {@inheritdoc}
36    */
37   public static function create(ContainerInterface $container) {
38     return new static(
39       $container->get('plugin.manager.block')
40     );
41   }
42
43   /**
44    * Retrieves suggestions for block category autocompletion.
45    *
46    * @param \Symfony\Component\HttpFoundation\Request $request
47    *   The current request.
48    *
49    * @return \Symfony\Component\HttpFoundation\JsonResponse
50    *   A JSON response containing autocomplete suggestions.
51    */
52   public function autocomplete(Request $request) {
53     $typed_category = $request->query->get('q');
54     $matches = [];
55     foreach ($this->blockManager->getCategories() as $category) {
56       if (stripos($category, $typed_category) === 0) {
57         $matches[] = ['value' => $category, 'label' => Html::escape($category)];
58       }
59     }
60     return new JsonResponse($matches);
61   }
62
63 }