You are here

function menu_link_content_entity_predelete in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/menu_link_content/menu_link_content.module \menu_link_content_entity_predelete()
  2. 9 core/modules/menu_link_content/menu_link_content.module \menu_link_content_entity_predelete()

Implements hook_entity_predelete().

File

core/modules/menu_link_content/menu_link_content.module, line 101
Allows administrators to create custom menu links.

Code

function menu_link_content_entity_predelete(EntityInterface $entity) {

  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $entity_type_id = $entity
    ->getEntityTypeId();
  foreach ($entity
    ->uriRelationships() as $rel) {
    $url = $entity
      ->toUrl($rel);

    // Entities can provide uri relationships that are not routed, in this case
    // getRouteParameters() will throw an exception.
    if (!$url
      ->isRouted()) {
      continue;
    }
    $route_parameters = $url
      ->getRouteParameters();
    if (!isset($route_parameters[$entity_type_id])) {

      // Do not delete links which do not relate to this exact entity. For
      // example, "collection", "add-form", etc.
      continue;
    }

    // Delete all MenuLinkContent links that point to this entity route.
    $result = $menu_link_manager
      ->loadLinksByRoute($url
      ->getRouteName(), $route_parameters);
    if ($result) {
      foreach ($result as $id => $instance) {
        if ($instance
          ->isDeletable() && strpos($id, 'menu_link_content:') === 0) {
          $instance
            ->deleteLink();
        }
      }
    }
  }
}