FallbackController.php in Entity Language Fallback 8
File
src/FallbackController.php
View source
<?php
namespace Drupal\entity_language_fallback;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\language\Entity\ConfigurableLanguage;
class FallbackController implements FallbackControllerInterface {
protected $fallback_chain;
protected $entityBundleCandidates;
protected $languageManager;
public function __construct(LanguageManagerInterface $languageManager, EntityTypeManagerInterface $entityTypeManager) {
$this->languageManager = $languageManager;
$this->entityTypeManager = $entityTypeManager;
$this->fallback_chain = [];
$this->entityBundleCandidates = [];
}
public function getFallbackChain($lang_code) {
$this
->ensureFallbackChain($lang_code);
return $this->fallback_chain[$lang_code];
}
public function getEntityFallbackCandidates(ContentEntityInterface $entity, $language_code) {
$cid = "{$entity->getEntityType()->id()}:{$entity->bundle()}";
if (isset($this->entityBundleCandidates[$cid])) {
return $this->entityBundleCandidates[$cid];
}
$candidates = [];
if ($entity
->isTranslatable()) {
$candidates[$language_code] = $language_code;
foreach ($this
->getFallbackChain($language_code) as $fallback_langcode) {
if (!(empty($fallback_langcode) || isset($candidates[$fallback_langcode]))) {
$candidates[$fallback_langcode] = $fallback_langcode;
}
}
}
$this->entityBundleCandidates[$cid] = $candidates;
return $candidates;
}
public function getTranslation($lang_code, ContentEntityInterface $entity) {
$this
->ensureFallbackChain($lang_code);
foreach ($this->fallback_chain[$lang_code] as $candidate) {
if ($entity
->hasTranslation($candidate)) {
return $entity
->getTranslation($candidate);
}
}
return FALSE;
}
protected function ensureFallbackChain($lang_code) {
if (isset($this->fallback_chain[$lang_code])) {
return;
}
$this->fallback_chain[$lang_code] = ($language = ConfigurableLanguage::load($lang_code)) ? $language
->getThirdPartySetting('entity_language_fallback', 'fallback_langcodes', []) : [];
}
public function getTranslations(ContentEntityInterface $entity) {
$translations = [];
foreach ($this->languageManager
->getLanguages() as $langcode => $language) {
if ($entity
->hasTranslation($langcode)) {
$translations[$langcode] = $entity
->getTranslation($langcode);
}
elseif ($fallback = $this
->getTranslation($langcode, $entity)) {
$translations[$langcode] = $fallback;
}
}
return $translations;
}
}