Skip to content

Instantly share code, notes, and snippets.

@fredysan
Last active January 20, 2020 22:18
Show Gist options
  • Save fredysan/b1452709280ed3c14d7768ae122b7e24 to your computer and use it in GitHub Desktop.
Save fredysan/b1452709280ed3c14d7768ae122b7e24 to your computer and use it in GitHub Desktop.
Sort menu Items - Drupal 8
<?php
namespace Drupal\wb_theme\Plugin\Preprocess;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
*
*/
class Menu implements ContainerFactoryPluginInterface {
/**
* Menu Link Tree Interface.
*
* @var \Drupal\Core\Menu\MenuLinkTreeInterface
* Menu tree service.
*/
protected $menuTree;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MenuLinkTreeInterface $menu_link_tree) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->menuTree = $menu_link_tree;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('menu.link_tree')
);
}
/**
* Get a menu tree.
*
* @param string $name
* Menu name.
*
* @return array
* Menu tree.
*/
public function getMenuTree($name) {
// @see https://www.drupal.org/project/drupal/issues/3019572#comment-13131191.
$parameters = $this->menuTree->getCurrentRouteMenuTreeParameters($name);
$tree = $this->menuTree->load($name, $parameters);
// Sort menu items.
// @see: https://www.drupal.org/project/drupal/issues/3015631#comment-13155444.
$manipulators = [
['callable' => 'menu.default_tree_manipulators:checkAccess'],
['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];
$tree = $this->menuTree->transform($tree, $manipulators);
return $tree;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment