You are here

MenuBlockTitle.php in Menu block title 8

File

src/MenuBlockTitle.php
View source
<?php

namespace Drupal\menu_block_title;

use Drupal\Core\Security\TrustedCallbackInterface;

/**
 * Provides methods for preRender hook.
 */
class MenuBlockTitle implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return [
      'preRender',
    ];
  }

  /**
   * The preRender callback which modifies the build output.
   */
  public static function preRender($build) {
    if (!isset($build['#derivative_plugin_id'])) {
      return $build;
    }
    $menu_name = $build['#derivative_plugin_id'];
    $active_menu_item = \Drupal::service('menu.active_trail')
      ->getActiveLink($menu_name);
    if (!$active_menu_item) {
      return $build;
    }

    // If a parent exists, load and use as title.
    if ($active_menu_item
      ->getParent()) {
      $parent_uuid = str_replace('menu_link_content:', '', $active_menu_item
        ->getParent());
      $parent = \Drupal::service('entity.repository')
        ->loadEntityByUuid('menu_link_content', $parent_uuid);
      $linked_title = [
        '#type' => 'link',
        '#url' => $parent
          ->getUrlObject(),
        '#title' => $parent
          ->getTitle(),
      ];
    }
    else {
      return $build;
    }
    $build['#configuration']['label'] = $linked_title;
    return $build;
  }

}

Classes

Namesort descending Description
MenuBlockTitle Provides methods for preRender hook.