function menu_node_prepare

Implements hook_node_prepare().

File

drupal/core/modules/menu/menu.module, line 490
Allows administrators to customize the site's navigation menus.

Code

function menu_node_prepare(EntityInterface $node) {
  if (empty($node->menu)) {

    // Prepare the node for the edit form so that $node->menu always exists.
    $menu_name = strtok(variable_get('menu_parent_' . $node->type, 'main:0'), ':');
    $menu_link = FALSE;
    if (isset($node->nid)) {
      $mlid = FALSE;

      // Give priority to the default menu
      $type_menus = variable_get('menu_options_' . $node->type, array(
        'main' => 'main',
      ));
      if (in_array($menu_name, $type_menus)) {
        $query = Drupal::entityQuery('menu_link')
          ->condition('link_path', 'node/' . $node->nid)
          ->condition('menu_name', $menu_name)
          ->condition('module', 'menu')
          ->sort('mlid', 'ASC')
          ->range(0, 1);
        $result = $query
          ->execute();
        $mlid = !empty($result) ? reset($result) : FALSE;
      }

      // Check all allowed menus if a link does not exist in the default menu.
      if (!$mlid && !empty($type_menus)) {
        $query = Drupal::entityQuery('menu_link')
          ->condition('link_path', 'node/' . $node->nid)
          ->condition('menu_name', array_values($type_menus), 'IN')
          ->condition('module', 'menu')
          ->sort('mlid', 'ASC')
          ->range(0, 1);
        $result = $query
          ->execute();
        $mlid = !empty($result) ? reset($result) : FALSE;
      }
      if ($mlid) {
        $menu_link = menu_link_load($mlid);
      }
    }
    if (!$menu_link) {
      $menu_link = entity_create('menu_link', array(
        'mlid' => 0,
        'plid' => 0,
        'menu_name' => $menu_name,
      ));
    }

    // Set default values.
    $node->menu = $menu_link;
  }

  // Find the depth limit for the parent select.
  if (!isset($node->menu['parent_depth_limit'])) {
    $node->menu['parent_depth_limit'] = _menu_parent_depth_limit($node->menu);
  }
}