public function EntityRepository::getTranslationFromContext in Drupal 8
Same name and namespace in other branches
- 9 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()
2 calls to EntityRepository::getTranslationFromContext()
- EntityRepository::getActiveMultiple in core/
lib/ Drupal/ Core/ Entity/ EntityRepository.php - Retrieves the active entity variants matching the specified context.
- EntityRepository::getCanonicalMultiple in core/
lib/ Drupal/ Core/ Entity/ EntityRepository.php - Retrieves the canonical entity variants matching the specified context.
File
- core/
lib/ Drupal/ Core/ Entity/ EntityRepository.php, line 99
Class
- EntityRepository
- Provides several mechanisms for retrieving entities.
Namespace
Drupal\Core\EntityCode
public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = []) {
$translation = $entity;
if ($entity instanceof TranslatableDataInterface && 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 += [
'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;
}