getUrlObject example


      '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;
      }
    }
    $this->assertEquals(1, $children);
    $this->assertTrue($google_found);
    // Now find the custom link under a system link.     $parameters->root = 'system.admin_structure';
    $tree = $menu_link_tree_service->load(static::MENU_NAME, $parameters);
    $found = FALSE;
    foreach ($tree as $menu_link_tree_element) {
      

  protected function menuLinkCheckAccess(MenuLinkInterface $instance) {
    $access_result = NULL;
    if ($this->account->hasPermission('link to any page')) {
      $access_result = AccessResult::allowed();
    }
    else {
      $url = $instance->getUrlObject();

      // When no route name is specified, this must be an external link.       if (!$url->isRouted()) {
        $access_result = AccessResult::allowed();
      }
      else {
        $access_result = $this->accessManager->checkNamedRoute($url->getRouteName()$url->getRouteParameters()$this->account, TRUE);
      }
    }
    return $access_result->cachePerPermissions();
  }

  
return (int) $this->get('weight')->value;
  }

  /** * {@inheritdoc} */
  public function getPluginDefinition() {
    $definition = [];
    $definition['class'] = 'Drupal\menu_link_content\Plugin\Menu\MenuLinkContent';
    $definition['menu_name'] = $this->getMenuName();

    if ($url_object = $this->getUrlObject()) {
      $definition['url'] = NULL;
      $definition['route_name'] = NULL;
      $definition['route_parameters'] = [];
      if (!$url_object->isRouted()) {
        $definition['url'] = $url_object->getUri();
      }
      else {
        $definition['route_name'] = $url_object->getRouteName();
        $definition['route_parameters'] = $url_object->getRouteParameters();
      }
      $definition['options'] = $url_object->getOptions();
    }
// Only render accessible links.       if (!$element->access->isAllowed()) {
        continue;
      }

      /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
      $link = $element->link;
      if ($link) {
        $id = 'menu_plugin_id:' . $link->getPluginId();
        $form[$id]['#item'] = $element;
        $form[$id]['#attributes'] = $link->isEnabled() ? ['class' => ['menu-enabled']] : ['class' => ['menu-disabled']];
        $form[$id]['title'] = Link::fromTextAndUrl($link->getTitle()$link->getUrlObject())->toRenderable();
        if (!$link->isEnabled()) {
          $form[$id]['title']['#suffix'] = ' (' . $this->t('disabled') . ')';
        }
        // @todo Remove this in https://www.drupal.org/node/2568785.         elseif ($id === 'menu_plugin_id:user.logout') {
          $form[$id]['title']['#suffix'] = ' (' . $this->t('<q>Log in</q> for anonymous users') . ')';
        }
        // @todo Remove this in https://www.drupal.org/node/2568785.         elseif (($url = $link->getUrlObject()) && $url->isRouted() && $url->getRouteName() == 'user.page') {
          $form[$id]['title']['#suffix'] = ' (' . $this->t('logged in users only') . ')';
        }

        
    // expect the main menu to display).     $this->drupalGet('');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->linkExists($view['page[link_properties][title]']);
    $this->assertSession()->linkByHrefExists(Url::fromUri('base:' . $view['page[path]'])->toString());

    // Make sure the link is associated with the main menu.     /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
    $link = $menu_link_manager->createInstance('views_view:views.' . $view['id'] . '.page_1');
    $url = $link->getUrlObject();
    $this->assertEquals('view.' . $view['id'] . '.page_1', $url->getRouteName()new FormattableMarkup('Found a link to %path in the main menu', ['%path' => $view['page[path]']]));
    $metadata = $link->getMetaData();
    $this->assertEquals(['view_id' => $view['id'], 'display_id' => 'page_1']$metadata);
  }

}
// @todo Bubble cacheability metadata of both accessible and         // inaccessible links. Currently made impossible by the way admin         // blocks are rendered.         continue;
      }

      /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
      $link = $element->link;
      $content[$key]['title'] = $link->getTitle();
      $content[$key]['options'] = $link->getOptions();
      $content[$key]['description'] = $link->getDescription();
      $content[$key]['url'] = $link->getUrlObject();
    }
    ksort($content);
    return $content;
  }

}
$form['info'] = [
      '#type' => 'item',
      '#title' => $this->t('This link is provided by the @name module. The title and path cannot be edited.', ['@name' => $this->moduleHandler->getName($provider)]),
    ];
    $form['id'] = [
      '#type' => 'value',
      '#value' => $this->menuLink->getPluginId(),
    ];
    $link = [
      '#type' => 'link',
      '#title' => $this->menuLink->getTitle(),
      '#url' => $this->menuLink->getUrlObject(),
    ];
    $form['path'] = [
      'link' => $link,
      '#type' => 'item',
      '#title' => $this->t('Link'),
    ];

    $form['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable menu link'),
      '#description' => $this->t('Menu links that are not enabled will not be listed in any menu.'),
      
// Set a helper variable to indicate whether the link is in the active       // trail.       $element['in_active_trail'] = FALSE;
      if ($data->inActiveTrail) {
        $element['in_active_trail'] = TRUE;
      }

      // Note: links are rendered in the menu.html.twig template; and they       // automatically bubble their associated cacheability metadata.       $element['attributes'] = new Attribute();
      $element['title'] = $link->getTitle();
      $element['url'] = $link->getUrlObject();
      $element['url']->setOption('set_active_class', TRUE);
      $element['below'] = $data->subtree ? $this->buildItems($data->subtree, $tree_access_cacheability$tree_link_cacheability) : [];
      if (isset($data->options)) {
        $element['url']->setOptions(NestedArray::mergeDeep($element['url']->getOptions()$data->options));
      }
      $element['original_link'] = $link;
      // Index using the link's unique ID.       $items[$link->getPluginId()] = $element;
    }

    return $items;
  }
/** * Tests output on administrative listing pages. */
  public function testAdminPages() {
    // Go to Administration.     $this->drupalGet('admin');

    // Verify that all visible, top-level administration links are listed on     // the main administration page.     foreach ($this->getTopLevelMenuLinks() as $item) {
      $this->assertSession()->linkExists($item->getTitle());
      $this->assertSession()->linkByHrefExists($item->getUrlObject()->toString());
      // The description should appear below the link.       $this->assertSession()->pageTextContains($item->getDescription());
    }

    // For each administrative listing page on which the Locale module appears,     // verify that there are links to the module's primary configuration pages,     // but no links to its individual sub-configuration pages. Also verify that     // a user with access to only some Locale module administration pages only     // sees links to the pages they have access to.     $admin_list_pages = [
      'admin/index',
      
// Verify expected breadcrumbs for menu links.     $trail = $home;
    $tree = [];
    // Logout the user because we want to check the active class as well, which     // is just rendered as anonymous user.     $this->drupalLogout();
    foreach ($tags as $name => $data) {
      $term = $data['term'];
      /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */
      $link = $data['link'];

      $link_path = $link->getUrlObject()->getInternalPath();
      $tree += [
        $link_path => $link->getTitle(),
      ];
      $this->assertBreadcrumb($link_path$trail$term->getName()$tree, TRUE, 'menu__item--active-trail');
      // Ensure that the tagged node is found.       $this->assertSession()->assertEscaped($parent->getTitle());

      // Additionally make sure that this link appears only once; i.e., the       // untranslated menu links automatically generated from menu router items       // ('taxonomy/term/%') should never be translated and appear in any menu       // other than the breadcrumb trail.
$child1_pending_revision->set('title', $pending_child1_title);
    $child1_pending_revision->set('link', [['uri' => 'internal:/#test']]);

    $violations = $child1_pending_revision->validate();
    $this->assertEmpty($violations);
    $child1_pending_revision->save();

    $storage->resetCache();
    $child1_pending_revision = $storage->loadRevision($child1_pending_revision->getRevisionId());
    $this->assertFalse($child1_pending_revision->isDefaultRevision());
    $this->assertEquals($pending_child1_title$child1_pending_revision->getTitle());
    $this->assertEquals('/#test', $child1_pending_revision->getUrlObject()->toString());

    // Check that saving a pending revision does not affect the menu tree.     $menu_tree = \Drupal::menuTree()->load('menu_test', new MenuTreeParameters());
    $parent_link = reset($menu_tree);
    $this->assertEquals($default_root_1_title$parent_link->link->getTitle());
    $this->assertEquals('/#root_1', $parent_link->link->getUrlObject()->toString());

    $child1_link = reset($parent_link->subtree);
    $this->assertEquals($default_child1_title$child1_link->link->getTitle());
    $this->assertEquals('/#child1', $child1_link->link->getUrlObject()->toString());

    
$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.     $path_alias->delete();
    $tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
    $this->assertTrue(isset($tree[$menu_link_content->getPluginId()]));
    $this->assertEquals('', $tree[$menu_link_content->getPluginId()]->link->getRouteName());
    // Verify the plugin now references a path that does not match any route.     $this->assertEquals('base:my-blog', $tree[$menu_link_content->getPluginId()]->link->getUrlObject()->getUri());
  }

}
case 'update':
        if (!$account->hasPermission('administer menu')) {
          return AccessResult::neutral("The 'administer menu' permission is required.")->cachePerPermissions();
        }
        else {
          // Assume that access is allowed.           $access = AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
          /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
          // If the link is routed determine whether the user has access unless           // they have the 'link to any page' permission.           if (!$account->hasPermission('link to any page') && ($url_object = $entity->getUrlObject()) && $url_object->isRouted()) {
            $link_access = $this->accessManager->checkNamedRoute($url_object->getRouteName()$url_object->getRouteParameters()$account, TRUE);
            $access = $access->andIf($link_access);
          }
          return $access;
        }

      case 'delete':
        return AccessResult::allowedIfHasPermission($account, 'administer menu')
          ->andIf(AccessResult::allowedIf(!$entity->isNew())->addCacheableDependency($entity));

      default:
        
$subtree = $menu_tree->build($element->subtree);
        $output = $renderer->executeInRenderContext(new RenderContext()function D) use ($renderer$subtree) {
          return $renderer->render($subtree);
        });
        $cacheability = $cacheability->merge(CacheableMetadata::createFromRenderArray($subtree));
      }
      else {
        $output = '';
      }
      // Many routes have dots as route name, while some special ones like       // <front> have <> characters in them.       $url = $link->getUrlObject();
      $id = str_replace(['.', '<', '>']['-', '', '']$url->isRouted() ? $url->getRouteName() : $url->getUri());

      $subtrees[$id] = $output;
    }

    // Store the subtrees, along with the cacheability metadata.     $cacheability->applyTo($data);
    $data['#subtrees'] = $subtrees;

    return $data;
  }

  
    foreach (array_values($tree) as $index => $element) {
      // Extract and preserve the access cacheability metadata.       $element_access = $element->access;
      assert($element_access instanceof AccessResultInterface);
      $cacheability->addCacheableDependency($element_access);
      // If an element is not accessible, it should not be encoded. Its       // cacheability should be preserved regardless, which is why that is done       // outside of this conditional.       if ($element_access->isAllowed()) {
        // Get and generate the URL of the link's target. This can create         // cacheability metadata also.         $url = $element->link->getUrlObject();
        $generated_url = $url->toString(TRUE);
        $cacheability = $cacheability->addCacheableDependency($generated_url);
        // Take the hierarchy value for the current element and append it         // to the link element parent's hierarchy value. See this method's         // docblock for more context on why this value is the way it is.         $hierarchy = $hierarchy_ancestors;
        array_push($hierarchystrval($index));
        $link_options = $element->link->getOptions();
        $link_attributes = ($link_options['attributes'] ?? []);
        $link_rel = $link_attributes['rel'] ?? 'item';
        // Encode the link.
Home | Imprint | This part of the site doesn't use cookies.