You are here

function menu_position_tokens_alter in Menu Position 7

Implements hook_tokens_alter().

File

./menu_position.module, line 680
Provides dynamic menu links based on configurable rules.

Code

function menu_position_tokens_alter(array &$replacements, array $context) {

  // This behaviour depends upon the contrib tokens module.
  // @see menu_tokens() in token.tokens.inc
  if (!module_exists('token')) {
    return;
  }
  $options = $context['options'];
  $sanitize = !empty($options['sanitize']);
  if ($context['type'] == 'node' && !empty($context['data']['node'])) {
    $node = $context['data']['node'];
    $tokens = $context['tokens'];

    // If the 'menu-link' token is present and no replacement value was
    // generated for it, try using the menu position rules instead.
    if (array_key_exists('menu-link', $tokens)) {
      $original = $tokens['menu-link'];
      if (empty($replacements[$original])) {
        if ($link = menu_position_token_menu_link_load($node)) {

          // We found a menu position rule, but the chances of us ever
          // wanting to use the *title* of a menu position rule's menu link
          // are vanishingly small, so we'll use the node title instead.
          $replacements[$original] = $sanitize ? check_plain($node->title) : $node->title;
        }
      }
    }

    // Process tokens that chain from a 'menu-link' token.
    if ($menu_tokens = token_find_with_prefix($tokens, 'menu-link')) {
      foreach ($menu_tokens as $token => $original) {
        if (empty($replacements[$original])) {

          // No replacement value was generated for this token, so now we
          // want to try the menu position rules. We need to unset its key
          // from the replacements array in order to merge in a new value.
          unset($replacements[$original]);
        }
        else {

          // This token was successfully replaced using the standard
          // 'menu-link' processing, so do not re-process it here.
          unset($menu_tokens[$token]);
        }
      }
      if ($menu_tokens) {
        if ($link = menu_position_token_menu_link_load($node)) {
          $data = array(
            'menu-link' => $link,
          );
          $replacements += token_generate('menu-link', $menu_tokens, $data, $options);
        }
      }
    }
  }
}