function language_hierarchy_fix_url_from_fallback in Language Hierarchy 8
Same name and namespace in other branches
- 2.x language_hierarchy.module \language_hierarchy_fix_url_from_fallback()
 
Replaces the URL language if it is just a fallback translation.
1 call to language_hierarchy_fix_url_from_fallback()
- language_hierarchy_preprocess_image_formatter in ./
language_hierarchy.module  - Implements hook_preprocess_image_formatter().
 
File
- ./
language_hierarchy.module, line 443  - Add sublanguage handling functionality to Drupal.
 
Code
function language_hierarchy_fix_url_from_fallback(Url $url, TranslatableInterface $translatable) {
  /** @var \Drupal\Core\Language\LanguageInterface $url_language */
  $url_language = $url
    ->getOption('language');
  // Respect a 'language_hierarchy_fallback' option, which flags that the URL
  // language is set intentionally. This allows directly linking to a fallback
  // language, as we would otherwise assume the link is intended for the current
  // page content language.
  if ($url_language && !$url
    ->getOption('language_hierarchy_fallback')) {
    $entity_type = $translatable
      ->getEntityTypeId();
    if ($url
      ->isRouted() && $url
      ->getRouteName() === 'entity.' . $entity_type . '.canonical') {
      // Check if the linked translation is just the closest fallback candidate
      // for the current page language.
      $page_language = \Drupal::languageManager()
        ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
      $candidate_langcode = $page_language
        ->getId();
      $url_langcode = $url_language
        ->getId();
      // Only proceed if the URL language is something other than the current
      // page content language.
      if ($url_langcode !== $candidate_langcode) {
        while ($candidate_langcode && $candidate_langcode !== $url_langcode && !$translatable
          ->hasTranslation($candidate_langcode)) {
          $language_config = ConfigurableLanguage::load($candidate_langcode);
          $candidate_langcode = $language_config
            ->getThirdPartySetting('language_hierarchy', 'fallback_langcode', '');
        }
        // If a fallback translation was found, which matches the URL language,
        // replace the language on the link with the current page content
        // language as it is just the fallback for the current page.
        if ($candidate_langcode && $candidate_langcode === $url_langcode && $translatable
          ->hasTranslation($candidate_langcode)) {
          $url
            ->setOption('language', $page_language);
          // Record that the language on this link has now been fixed.
          $url
            ->setOption('language_hierarchy_fallback', TRUE);
        }
      }
    }
  }
  return $url;
}