MenuSelectAutocompleteController.php in Menu Select 2.0.x
File
src/Controller/MenuSelectAutocompleteController.php
View source
<?php
namespace Drupal\menu_select\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\menu_select\MenuSelectTreeBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class MenuSelectAutocompleteController extends ControllerBase {
protected $treeBuilder;
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->treeBuilder = $container
->get('menu_select.tree_builder');
return $instance;
}
public function autocomplete($menus, $max_depth, Request $request) {
$keyword = $request->query
->get('q');
$menu_ids = explode(':', $menus);
$matching_links = $this
->getMatchingLinks($keyword, $menu_ids, $max_depth);
$autocomplete = [];
foreach ($matching_links as $key => $label) {
$autocomplete[] = [
'value' => (string) $key,
'label' => $label,
];
}
return new JsonResponse($autocomplete);
}
protected function getMatchingLinks($keyword, array $menus, $max_depth) {
$options = [];
foreach ($menus as $menu_name) {
$tree = $this->treeBuilder
->loadMenuTree($menu_name, $max_depth);
$candidates = [];
$this
->buildCandidateLinks($tree, $menu_name, $candidates);
foreach ($candidates as $key => $menu_link_label) {
if (stripos($menu_link_label, $keyword) !== FALSE) {
$options[$key] = $menu_link_label;
}
}
}
return $options;
}
protected function buildCandidateLinks(array $tree, $menu_name, array &$options) {
foreach ($tree as $data) {
$title = $data->link
->getTitle();
$options[$menu_name . ':' . $data->link
->getPluginId()] = $title;
if (!empty($data->subtree)) {
$this
->buildCandidateLinks($data->subtree, $menu_name, $options);
}
}
}
}