Skip to content

Commit

Permalink
Prevent errors with mega menu block if menu link content entities dis…
Browse files Browse the repository at this point in the history
…appear for some reason
  • Loading branch information
berliner committed Dec 4, 2024
1 parent ded7dfc commit 26b2501
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions html/modules/custom/ghi_menu/src/Plugin/Block/MegaMenuBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Drupal\ghi_menu\Plugin\Block;

use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Utility\Html;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
Expand All @@ -13,6 +14,7 @@
use Drupal\Core\Render\Element\RenderElement;
use Drupal\Core\Render\Element\VerticalTabs;
use Drupal\ghi_blocks\Traits\VerticalTabsTrait;
use Drupal\menu_link_content\Plugin\Menu\MenuLinkContent;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
Expand Down Expand Up @@ -56,6 +58,13 @@ class MegaMenuBlock extends BlockBase implements ContainerFactoryPluginInterface
*/
protected $menuTree;

/**
* The menu tree manipulators.
*
* @var \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators
*/
protected $menuTreeManipulators;

/**
* {@inheritdoc}
*/
Expand All @@ -66,6 +75,7 @@ public static function create(ContainerInterface $container, array $configuratio
$instance->entityFieldManager = $container->get('entity_field.manager');
$instance->moduleHandler = $container->get('module_handler');
$instance->menuTree = $container->get('menu.link_tree');
$instance->menuTreeManipulators = $container->get('menu.default_tree_manipulators');
return $instance;
}

Expand Down Expand Up @@ -206,6 +216,8 @@ public function getMenuItems() {
$parameters = $this->menuTree->getCurrentRouteMenuTreeParameters('main');
$parameters->expandedParents = [];
$menu_tree = $this->menuTree->load($menu->id(), $parameters);
$this->filterBrokenItems($menu_tree);

// Transform the tree using the manipulators you want.
$manipulators = [
// Only show links that are accessible for the current user.
Expand All @@ -217,6 +229,31 @@ public function getMenuItems() {
return $menu_tree;
}

/**
* Filter broken menu links from the tree.
*
* @param \Drupal\Core\Menu\MenuLinkTreeElement[] $menu_tree
* The menu tree to filter.
*/
private function filterBrokenItems(array &$menu_tree) {
foreach ($menu_tree as $key => &$item) {
$link = $item->link;
if (!$link instanceof MenuLinkContent) {
continue;
}
try {
$this->menuTreeManipulators->checkAccess([$item]);
}
catch (PluginException $e) {
unset($menu_tree[$key]);
continue;
}
if ($item->hasChildren) {
$this->filterBrokenItems($item->subtree);
}
}
}

/**
* {@inheritdoc}
*/
Expand Down

0 comments on commit 26b2501

Please sign in to comment.