function ContentTranslationHooks::languageFallbackCandidatesEntityViewAlter

Implements hook_language_fallback_candidates_OPERATION_alter().

Performs language fallback for inaccessible translations.

File

core/modules/content_translation/src/Hook/ContentTranslationHooks.php, line 387

Class

ContentTranslationHooks
Hook implementations for content_translation.

Namespace

Drupal\content_translation\Hook

Code

public function languageFallbackCandidatesEntityViewAlter(&$candidates, $context) : void {
    
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $context['data'];
    $entity_type_id = $entity->getEntityTypeId();
    
    /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
    $manager = \Drupal::service('content_translation.manager');
    if ($manager->isEnabled($entity_type_id, $entity->bundle())) {
        
        /** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
        $handler = \Drupal::entityTypeManager()->getHandler($entity->getEntityTypeId(), 'translation');
        foreach ($entity->getTranslationLanguages() as $langcode => $language) {
            $metadata = $manager->getTranslationMetadata($entity->getTranslation($langcode));
            if (!$metadata->isPublished()) {
                $access = $handler->getTranslationAccess($entity, 'update');
                $entity->addCacheableDependency($access);
                if (!$access->isAllowed()) {
                    // If the user has no translation update access, also check view
                    // access for that translation, to allow other modules to allow access
                    // to unpublished translations.
                    $access = $entity->getTranslation($langcode)
                        ->access('view', NULL, TRUE);
                    $entity->addCacheableDependency($access);
                    if (!$access->isAllowed()) {
                        unset($candidates[$langcode]);
                    }
                }
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.