You are here

public function EntityRepository::getTranslationFromContext in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Entity/EntityRepository.php \Drupal\Core\Entity\EntityRepository::getTranslationFromContext()

Gets the entity translation to be used in the given context.

This will check whether a translation for the desired language is available and if not, it will fall back to the most appropriate translation based on the provided context.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity whose translation will be returned.

string $langcode: (optional) The language of the current context. Defaults to the current content language.

array $context: (optional) An associative array of arbitrary data that can be useful to determine the proper fallback sequence.

Return value

\Drupal\Core\Entity\EntityInterface An entity object for the translated data.

Overrides EntityRepositoryInterface::getTranslationFromContext

See also

\Drupal\Core\Language\LanguageManagerInterface::getFallbackCandidates()

File

core/lib/Drupal/Core/Entity/EntityRepository.php, line 87
Contains \Drupal\Core\Entity\EntityRepository.

Class

EntityRepository
Provides several mechanisms for retrieving entities.

Namespace

Drupal\Core\Entity

Code

public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
  $translation = $entity;
  if ($entity instanceof TranslatableInterface && count($entity
    ->getTranslationLanguages()) > 1) {
    if (empty($langcode)) {
      $langcode = $this->languageManager
        ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
        ->getId();
      $entity
        ->addCacheContexts([
        'languages:' . LanguageInterface::TYPE_CONTENT,
      ]);
    }

    // Retrieve language fallback candidates to perform the entity language
    // negotiation, unless the current translation is already the desired one.
    if ($entity
      ->language()
      ->getId() != $langcode) {
      $context['data'] = $entity;
      $context += array(
        'operation' => 'entity_view',
        'langcode' => $langcode,
      );
      $candidates = $this->languageManager
        ->getFallbackCandidates($context);

      // Ensure the default language has the proper language code.
      $default_language = $entity
        ->getUntranslated()
        ->language();
      $candidates[$default_language
        ->getId()] = LanguageInterface::LANGCODE_DEFAULT;

      // Return the most fitting entity translation.
      foreach ($candidates as $candidate) {
        if ($entity
          ->hasTranslation($candidate)) {
          $translation = $entity
            ->getTranslation($candidate);
          break;
        }
      }
    }
  }
  return $translation;
}