menu_item_fields-8.x-1.5/src/Render/Callback.php
src/Render/Callback.php
<?php
namespace Drupal\menu_item_fields\Render;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Provides a trusted callback to alter a menu item markup.
*
* @see menu_item_fields_preprocess_menu()
*/
class Callback implements TrustedCallbackInterface {
/**
* {@inheritdoc}
*/
public static function trustedCallbacks(): array {
return ['preRenderMenuLinkContent'];
}
/**
* Fill the the link field with values from the menu item.
*
* @param array $element
* The menu item that is being displayed.
*/
public static function preRenderMenuLinkContent($element): array {
// Skip processing if the link field is not being displayed.
if (!isset($element['link'])) {
return $element;
}
$contentLink = &$element['link'][0];
$contentUrl = &$contentLink['#url'];
// Set the title attribute (description field) from the menu item.
$menuItemAttributes = $element['#menu_item']['url']->getOption('attributes');
if (isset($menuItemAttributes['title'])) {
$contentLinkAttributes = $contentUrl->getOption('attributes');
$contentLinkAttributes['title'] = $menuItemAttributes['title'];
$contentUrl->setOption('attributes', $contentLinkAttributes);
}
$contentUrl->setOption('set_active_class', $element['#menu_item']['url']->getOption('set_active_class'));
if (is_string($contentLink['#title'])) {
$contentLink['#title'] = $element['#menu_item']['title'];
}
return $element;
}
}
