MenuTreeParameters example

$edit = [];
    $edit['label'] = $this->randomMachineName(16);
    $view_id = $edit['id'] = strtolower($this->randomMachineName(16));
    $edit['description'] = $this->randomMachineName(16);
    $edit['page[create]'] = TRUE;
    $edit['page[path]'] = 'admin/foo';

    $this->drupalGet('admin/structure/views/add');
    $this->submitForm($edit, 'Save and edit');

    $parameters = new MenuTreeParameters();
    $parameters->addCondition('id', $menu_link_content->getPluginId());
    $result = \Drupal::menuTree()->load('admin', $parameters);
    $plugin_definition = end($result)->link->getPluginDefinition();
    $this->assertEquals('view.' . $view_id . '.page_1', $plugin_definition['route_name']);

    $this->clickLink('No menu');

    $this->submitForm([
      'menu[type]' => 'default tab',
      'menu[title]' => 'Menu title',
    ], 'Apply');

    
$this->configuration['level'] = $form_state->getValue('level');
    $this->configuration['depth'] = $form_state->getValue('depth');
    $this->configuration['expand_all_items'] = $form_state->getValue('expand_all_items');
  }

  /** * {@inheritdoc} */
  public function build() {
    $menu_name = $this->getDerivativeId();
    if ($this->configuration['expand_all_items']) {
      $parameters = new MenuTreeParameters();
      $active_trail = $this->menuActiveTrail->getActiveTrailIds($menu_name);
      $parameters->setActiveTrail($active_trail);
    }
    else {
      $parameters = $this->menuTree->getCurrentRouteMenuTreeParameters($menu_name);
    }

    // Adjust the menu tree parameters based on the block's configuration.     $level = $this->configuration['level'];
    $depth = $this->configuration['depth'];
    $parameters->setMinDepth($level);
    

  protected function buildOverviewForm(array &$form, FormStateInterface $form_state) {
    // Ensure that menu_overview_form_submit() knows the parents of this form     // section.     if (!$form_state->has('menu_overview_form_parents')) {
      $form_state->set('menu_overview_form_parents', []);
    }

    $form['#attached']['library'][] = 'menu_ui/drupal.menu_ui.adminforms';

    $tree = $this->menuTree->load($this->entity->id()new MenuTreeParameters());

    // We indicate that a menu administrator is running the menu access check.     $this->getRequest()->attributes->set('_menu_admin', TRUE);
    $manipulators = [
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ];
    $tree = $this->menuTree->transform($tree$manipulators);
    $this->getRequest()->attributes->set('_menu_admin', FALSE);

    // Determine the delta; the number of weights to be made available.

  public function getParentSelectOptions($id = '', array $menus = NULL, CacheableMetadata &$cacheability = NULL) {
    if (!isset($menus)) {
      $menus = $this->getMenuOptions();
    }

    $options = [];
    $depth_limit = $this->getParentDepthLimit($id);
    foreach ($menus as $menu_name => $menu_title) {
      $options[$menu_name . ':'] = '<' . $menu_title . '>';

      $parameters = new MenuTreeParameters();
      $parameters->setMaxDepth($depth_limit);
      $tree = $this->menuLinkTree->load($menu_name$parameters);
      $manipulators = [
        ['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
        ['callable' => 'menu.default_tree_manipulators:checkAccess'],
        ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
      ];
      $tree = $this->menuLinkTree->transform($tree$manipulators);
      $this->parentSelectOptionsTreeWalk($tree$menu_name, '--', $options$id$depth_limit$cacheability);
    }
    return $options;
  }

  public function testPathAliasChange() {
    $path_alias = $this->createPathAlias('/test-page', '/my-blog');
    $menu_link_content = MenuLinkContent::create([
      'title' => 'Menu title',
      'link' => ['uri' => 'internal:/my-blog'],
      'menu_name' => 'tools',
    ]);
    $menu_link_content->save();

    $tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
    $this->assertEquals('test_page_test.test_page', $tree[$menu_link_content->getPluginId()]->link->getPluginDefinition()['route_name']);

    // Saving an alias should clear the alias manager cache.     $path_alias->setPath('/test-render-title');
    $path_alias->setAlias('/my-blog');
    $path_alias->save();

    $tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
    $this->assertEquals('test_page_test.render_title', $tree[$menu_link_content->getPluginId()]->link->getPluginDefinition()['route_name']);

    // Delete the alias.
// Create "collection" menu link pointing to the user listing page.     $menu_link_content_collection = MenuLinkContent::create([
      'title' => 'users listing',
      'menu_name' => 'menu_test',
      'link' => [['uri' => 'internal:/' . $user->toUrl('collection')->getInternalPath()]],
      'bundle' => 'menu_test',
    ]);
    $menu_link_content_collection->save();

    // Check is menu links present in the menu.     $menu_tree_condition = (new MenuTreeParameters())->addCondition('route_name', 'entity.user.canonical');
    $this->assertCount(1, \Drupal::menuTree()->load('menu_test', $menu_tree_condition));
    $menu_tree_condition_collection = (new MenuTreeParameters())->addCondition('route_name', 'entity.user.collection');
    $this->assertCount(1, \Drupal::menuTree()->load('menu_test', $menu_tree_condition_collection));

    // Delete the user.     $user->delete();

    // The "canonical" menu item has to be deleted.     $this->assertCount(0, \Drupal::menuTree()->load('menu_test', $menu_tree_condition));

    // The "collection" menu item should still present in the menu.
$this->routeProvider = $route_provider;
    $this->menuActiveTrail = $menu_active_trail;
    $this->controllerResolver = $controller_resolver;
  }

  /** * {@inheritdoc} */
  public function getCurrentRouteMenuTreeParameters($menu_name) {
    $active_trail = $this->menuActiveTrail->getActiveTrailIds($menu_name);

    $parameters = new MenuTreeParameters();
    $parameters->setActiveTrail($active_trail)
      // We want links in the active trail to be expanded.       ->addExpandedParents($active_trail)
      // We marked the links in the active trail to be expanded, but we also       // want their descendants that have the "expanded" flag enabled to be       // expanded.       ->addExpandedParents($this->treeStorage->getExpanded($menu_name$active_trail));

    return $parameters;
  }

  


  /** * Returns all top level menu links. * * @return \Drupal\Core\Menu\MenuLinkInterface[] */
  protected function getTopLevelMenuLinks() {
    $menu_tree = \Drupal::menuTree();

    // The system.admin link is normally the parent of all top-level admin links.     $parameters = new MenuTreeParameters();
    $parameters->setRoot('system.admin')->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
    $tree = $menu_tree->load(NULL, $parameters);
    $manipulators = [
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      ['callable' => 'menu.default_tree_manipulators:flatten'],
    ];
    $tree = $menu_tree->transform($tree$manipulators);

    // Transform the tree to a list of menu links.     $menu_links = [];
    foreach ($tree as $element) {
      
/** * Tests deleting all the links in a menu. */
  public function testDeleteLinksInMenu() {
    \Drupal::entityTypeManager()->getStorage('menu')->create(['id' => 'menu1'])->save();
    \Drupal::entityTypeManager()->getStorage('menu')->create(['id' => 'menu2'])->save();

    \Drupal::entityTypeManager()->getStorage('menu_link_content')->create(['link' => ['uri' => 'internal:/menu_name_test'], 'menu_name' => 'menu1', 'bundle' => 'menu_link_content', 'title' => 'Link test'])->save();
    \Drupal::entityTypeManager()->getStorage('menu_link_content')->create(['link' => ['uri' => 'internal:/menu_name_test'], 'menu_name' => 'menu1', 'bundle' => 'menu_link_content', 'title' => 'Link test'])->save();
    \Drupal::entityTypeManager()->getStorage('menu_link_content')->create(['link' => ['uri' => 'internal:/menu_name_test'], 'menu_name' => 'menu2', 'bundle' => 'menu_link_content', 'title' => 'Link test'])->save();

    $output = $this->linkTree->load('menu1', new MenuTreeParameters());
    $this->assertCount(2, $output);
    $output = $this->linkTree->load('menu2', new MenuTreeParameters());
    $this->assertCount(1, $output);

    $this->menuLinkManager->deleteLinksInMenu('menu1');

    $output = $this->linkTree->load('menu1', new MenuTreeParameters());
    $this->assertCount(0, $output);

    $output = $this->linkTree->load('menu2', new MenuTreeParameters());
    $this->assertCount(1, $output);
  }
$this->assertEntity(478, 'und', 'custom link test', 'admin', NULL, TRUE, FALSE, ['attributes' => ['title' => '']], 'internal:/admin/content', 0);
    $this->assertEntity(479, 'und', 'node link test', 'tools', 'node 2', TRUE, FALSE, [
      'attributes' => ['title' => 'node 2'],
      'query' => [
        'name' => 'ferret',
        'color' => 'purple',
      ],
    ],
      'entity:node/2', 3);

    $menu_link_tree_service = \Drupal::service('menu.link_tree');
    $parameters = new MenuTreeParameters();
    $tree = $menu_link_tree_service->load(static::MENU_NAME, $parameters);
    $this->assertCount(2, $tree);
    $children = 0;
    $google_found = FALSE;
    foreach ($tree as $menu_link_tree_element) {
      $children += $menu_link_tree_element->hasChildren;
      if ($menu_link_tree_element->link->getUrlObject()->toString() == 'http://bing.com') {
        $this->assertEquals('http://google.com', reset($menu_link_tree_element->subtree)->link->getUrlObject()->toString());
        $google_found = TRUE;
      }
    }
    

  public function getAdminBlock(MenuLinkInterface $instance) {
    $content = [];
    // Only find the children of this link.     $link_id = $instance->getPluginId();
    $parameters = new MenuTreeParameters();
    $parameters->setRoot($link_id)->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
    $tree = $this->menuTree->load(NULL, $parameters);
    $manipulators = [
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ];
    $tree = $this->menuTree->transform($tree$manipulators);
    foreach ($tree as $key => $element) {
      // Only render accessible links.       if (!$element->access->isAllowed()) {
        // @todo Bubble cacheability metadata of both accessible and
return $data;
  }

  /** * Tests setMinDepth(). * * @covers ::setMinDepth * @dataProvider providerTestSetMinDepth */
  public function testSetMinDepth($min_depth$expected) {
    $parameters = new MenuTreeParameters();
    $parameters->setMinDepth($min_depth);
    $this->assertEquals($expected$parameters->minDepth);
  }

  /** * Tests addExpandedParents(). * * @covers ::addExpandedParents */
  public function testAddExpanded() {
    $parameters = new MenuTreeParameters();

    
'route_name_1' => new Route('/example-path'),
    ]);
    \Drupal::service('router.builder')->rebuild();

    // Set up a custom menu link pointing to a specific path.     $parent = MenuLinkContent::create([
      'title' => '<script>alert("Welcome to the discovered jungle!")</script>',
      'link' => [['uri' => 'internal:/example-path']],
      'menu_name' => 'tools',
    ]);
    $parent->save();
    $menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
    $this->assertCount(1, $menu_tree);
    /** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
    $tree_element = reset($menu_tree);
    $this->assertEquals('route_name_1', $tree_element->link->getRouteName());

    // Change the underlying route and trigger the rediscovering.     \Drupal::state()->set('menu_link_content_dynamic_route.routes', [
      'route_name_2' => new Route('/example-path'),
    ]);
    \Drupal::service('router.builder')->rebuild();

    

  public function overview($link_id) {
    // Check for status report errors.     if ($this->currentUser()->hasPermission('administer site configuration') && $this->systemManager->checkRequirements()) {
      $this->messenger()->addError($this->t('One or more problems were detected with your Drupal installation. Check the <a href=":status">status report</a> for more information.', [':status' => Url::fromRoute('system.status')->toString()]));
    }
    // Load all menu links below it.     $parameters = new MenuTreeParameters();
    $parameters->setRoot($link_id)->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
    $tree = $this->menuLinkTree->load(NULL, $parameters);
    $manipulators = [
      ['callable' => 'menu.default_tree_manipulators:checkAccess'],
      ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ];
    $tree = $this->menuLinkTree->transform($tree$manipulators);
    $tree_access_cacheability = new CacheableMetadata();
    $blocks = [];
    foreach ($tree as $key => $element) {
      $tree_access_cacheability = $tree_access_cacheability->merge(CacheableMetadata::createFromObject($element->access));

      

  public function testMoveToRoot() {
    /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $menu_link_manager->rebuild();

    $menu_link = $menu_link_manager->getDefinition('menu_test.child');
    $this->assertEquals('menu_test.parent', $menu_link['parent']);
    $this->assertEquals('test', $menu_link['menu_name']);

    $tree = \Drupal::menuTree()->load('test', new MenuTreeParameters());
    $this->assertCount(1, $tree);
    $this->assertEquals('menu_test.parent', $tree['menu_test.parent']->link->getPluginId());
    $this->assertEquals('menu_test.child', $tree['menu_test.parent']->subtree['menu_test.child']->link->getPluginId());

    // Ensure that the menu name is not forgotten.     $menu_link_manager->updateDefinition('menu_test.child', ['parent' => '']);
    $menu_link = $menu_link_manager->getDefinition('menu_test.child');

    $this->assertEquals('', $menu_link['parent']);
    $this->assertEquals('test', $menu_link['menu_name']);

    
Home | Imprint | This part of the site doesn't use cookies.