Commit 46942cd3 authored by catch's avatar catch

Issue #2019055 by plach, fago, kfritsche: Switch from field-level language...

Issue #2019055 by plach, fago, kfritsche: Switch from field-level language fallback to entity-level language fallback.
parent b9dfcae3
...@@ -218,7 +218,7 @@ services: ...@@ -218,7 +218,7 @@ services:
arguments: ['@event_dispatcher', '@service_container', '@controller_resolver'] arguments: ['@event_dispatcher', '@service_container', '@controller_resolver']
language_manager: language_manager:
class: Drupal\Core\Language\LanguageManager class: Drupal\Core\Language\LanguageManager
arguments: ['@state'] arguments: ['@state', '@module_handler']
string_translator.custom_strings: string_translator.custom_strings:
class: Drupal\Core\StringTranslation\Translator\CustomStrings class: Drupal\Core\StringTranslation\Translator\CustomStrings
arguments: ['@settings'] arguments: ['@settings']
......
...@@ -545,30 +545,6 @@ function language_url_split_prefix($path, $languages) { ...@@ -545,30 +545,6 @@ function language_url_split_prefix($path, $languages) {
return array(FALSE, $path); return array(FALSE, $path);
} }
/**
* Returns the possible fallback languages ordered by language weight.
*
* @param
* (optional) The language type. Defaults to Language::TYPE_CONTENT.
*
* @return
* An array of language codes.
*/
function language_fallback_get_candidates($type = Language::TYPE_CONTENT) {
$fallback_candidates = &drupal_static(__FUNCTION__);
if (!isset($fallback_candidates)) {
// Get languages ordered by weight, add Language::LANGCODE_NOT_SPECIFIED at the end.
$fallback_candidates = array_keys(language_list());
$fallback_candidates[] = Language::LANGCODE_NOT_SPECIFIED;
// Let other modules hook in and add/change candidates.
drupal_alter('language_fallback_candidates', $fallback_candidates);
}
return $fallback_candidates;
}
/** /**
* @} End of "language_negotiation" * @} End of "language_negotiation"
*/ */
...@@ -423,6 +423,12 @@ protected function getTranslatedField($property_name, $langcode) { ...@@ -423,6 +423,12 @@ protected function getTranslatedField($property_name, $langcode) {
*/ */
public function set($property_name, $value, $notify = TRUE) { public function set($property_name, $value, $notify = TRUE) {
$this->get($property_name)->setValue($value, FALSE); $this->get($property_name)->setValue($value, FALSE);
if ($property_name == 'langcode') {
// Avoid using unset as this unnecessarily triggers magic methods later
// on.
$this->language = NULL;
}
} }
/** /**
...@@ -658,6 +664,7 @@ protected function initializeTranslation($langcode) { ...@@ -658,6 +664,7 @@ protected function initializeTranslation($langcode) {
$translation->values = &$this->values; $translation->values = &$this->values;
$translation->fields = &$this->fields; $translation->fields = &$this->fields;
$translation->translations = &$this->translations; $translation->translations = &$this->translations;
$translation->enforceIsNew = &$this->enforceIsNew;
$translation->translationInitialize = FALSE; $translation->translationInitialize = FALSE;
return $translation; return $translation;
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
namespace Drupal\Core\Entity; namespace Drupal\Core\Entity;
use Drupal\Core\Language\Language; use Drupal\Core\Language\Language;
use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* Entity form controller variant for content entity types. * Entity form controller variant for content entity types.
...@@ -16,6 +17,32 @@ ...@@ -16,6 +17,32 @@
*/ */
class ContentEntityFormController extends EntityFormController { class ContentEntityFormController extends EntityFormController {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a ContentEntityFormController object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(EntityManagerInterface $entity_manager) {
$this->entityManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager')
);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
...@@ -38,6 +65,7 @@ public function form(array $form, array &$form_state) { ...@@ -38,6 +65,7 @@ public function form(array $form, array &$form_state) {
* {@inheritdoc} * {@inheritdoc}
*/ */
public function validate(array $form, array &$form_state) { public function validate(array $form, array &$form_state) {
$this->updateFormLangcode($form_state);
$entity = $this->buildEntity($form, $form_state); $entity = $this->buildEntity($form, $form_state);
$entity_type = $entity->entityType(); $entity_type = $entity->entityType();
$entity_langcode = $entity->language()->id; $entity_langcode = $entity->language()->id;
...@@ -73,53 +101,22 @@ public function validate(array $form, array &$form_state) { ...@@ -73,53 +101,22 @@ public function validate(array $form, array &$form_state) {
protected function init(array &$form_state) { protected function init(array &$form_state) {
// Ensure we act on the translation object corresponding to the current form // Ensure we act on the translation object corresponding to the current form
// language. // language.
$this->entity = $this->getTranslatedEntity($form_state);
parent::init($form_state);
}
/**
* Returns the translation object corresponding to the form language.
*
* @param array $form_state
* A keyed array containing the current state of the form.
*/
protected function getTranslatedEntity(array $form_state) {
$langcode = $this->getFormLangcode($form_state); $langcode = $this->getFormLangcode($form_state);
$translation = $this->entity->getTranslation($langcode); $this->entity = $this->entity->getTranslation($langcode);
// Ensure that the entity object is a BC entity if the original one is. parent::init($form_state);
return $this->entity instanceof EntityBCDecorator ? $translation->getBCEntity() : $translation;
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getFormLangcode(array $form_state) { public function getFormLangcode(array &$form_state) {
$entity = $this->entity; if (empty($form_state['langcode'])) {
if (!empty($form_state['langcode'])) { // Imply a 'view' operation to ensure users edit entities in the same
$langcode = $form_state['langcode']; // language they are displayed. This allows to keep contextual editing
} // working also for multilingual entities.
else { $form_state['langcode'] = $this->entityManager->getTranslationFromContext($this->entity)->language()->id;
// If no form langcode was provided we default to the current content
// language and inspect existing translations to find a valid fallback,
// if any.
$translations = $entity->getTranslationLanguages();
$languageManager = \Drupal::languageManager();
$langcode = $languageManager->getLanguage(Language::TYPE_CONTENT)->id;
$fallback = $languageManager->isMultilingual() ? language_fallback_get_candidates() : array();
while (!empty($langcode) && !isset($translations[$langcode])) {
$langcode = array_shift($fallback);
}
}
// If the site is not multilingual or no translation for the given form
// language is available, fall back to the entity language.
if (!empty($langcode)) {
return $langcode;
}
else {
// If the entity is translatable, return the original language.
return $entity->getUntranslated()->language()->id;
} }
return $form_state['langcode'];
} }
/** /**
...@@ -136,8 +133,8 @@ public function buildEntity(array $form, array &$form_state) { ...@@ -136,8 +133,8 @@ public function buildEntity(array $form, array &$form_state) {
$entity = clone $this->entity; $entity = clone $this->entity;
$entity_type = $entity->entityType(); $entity_type = $entity->entityType();
$info = entity_get_info($entity_type); $info = entity_get_info($entity_type);
// @todo Exploit the Field API to process the submitted entity fields.
// @todo Exploit the Entity Field API to process the submitted field values.
// Copy top-level form values that are entity fields but not handled by // Copy top-level form values that are entity fields but not handled by
// field API without changing existing entity fields that are not being // field API without changing existing entity fields that are not being
// edited by this form. Values of fields handled by field API are copied // edited by this form. Values of fields handled by field API are copied
...@@ -163,4 +160,5 @@ public function buildEntity(array $form, array &$form_state) { ...@@ -163,4 +160,5 @@ public function buildEntity(array $form, array &$form_state) {
} }
return $entity; return $entity;
} }
} }
...@@ -269,6 +269,7 @@ protected function actions(array $form, array &$form_state) { ...@@ -269,6 +269,7 @@ protected function actions(array $form, array &$form_state) {
* {@inheritdoc} * {@inheritdoc}
*/ */
public function validate(array $form, array &$form_state) { public function validate(array $form, array &$form_state) {
$this->updateFormLangcode($form_state);
// @todo Remove this. // @todo Remove this.
// Execute legacy global validation handlers. // Execute legacy global validation handlers.
unset($form_state['validate_handlers']); unset($form_state['validate_handlers']);
...@@ -292,8 +293,6 @@ public function validate(array $form, array &$form_state) { ...@@ -292,8 +293,6 @@ public function validate(array $form, array &$form_state) {
public function submit(array $form, array &$form_state) { public function submit(array $form, array &$form_state) {
// Remove button and internal Form API values from submitted values. // Remove button and internal Form API values from submitted values.
form_state_values_clean($form_state); form_state_values_clean($form_state);
$this->updateFormLangcode($form_state);
$this->entity = $this->buildEntity($form, $form_state); $this->entity = $this->buildEntity($form, $form_state);
return $this->entity; return $this->entity;
} }
...@@ -325,7 +324,7 @@ public function delete(array $form, array &$form_state) { ...@@ -325,7 +324,7 @@ public function delete(array $form, array &$form_state) {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getFormLangcode(array $form_state) { public function getFormLangcode(array &$form_state) {
return $this->entity->language()->id; return $this->entity->language()->id;
} }
......
...@@ -26,7 +26,7 @@ interface EntityFormControllerInterface extends BaseFormIdInterface { ...@@ -26,7 +26,7 @@ interface EntityFormControllerInterface extends BaseFormIdInterface {
* @return string * @return string
* The form language code. * The form language code.
*/ */
public function getFormLangcode(array $form_state); public function getFormLangcode(array &$form_state);
/** /**
* Checks whether the current form language matches the entity one. * Checks whether the current form language matches the entity one.
......
...@@ -91,7 +91,7 @@ public function bundle(); ...@@ -91,7 +91,7 @@ public function bundle();
* *
* @param $langcode * @param $langcode
* (optional) The language code of the language that should be used for * (optional) The language code of the language that should be used for
* getting the label. If set to NULL, the entity's default language is * getting the label. If set to NULL, the entity's active language is
* used. * used.
* *
* @return * @return
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
use Drupal\Component\Plugin\PluginManagerBase; use Drupal\Component\Plugin\PluginManagerBase;
use Drupal\Component\Plugin\Factory\DefaultFactory; use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\Component\Utility\NestedArray; use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManager; use Drupal\Core\Language\LanguageManager;
use Drupal\Core\Language\Language; use Drupal\Core\Language\Language;
...@@ -17,8 +18,8 @@ ...@@ -17,8 +18,8 @@
use Drupal\Core\Plugin\Discovery\CacheDecorator; use Drupal\Core\Plugin\Discovery\CacheDecorator;
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery; use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
use Drupal\Core\Plugin\Discovery\InfoHookDecorator; use Drupal\Core\Plugin\Discovery\InfoHookDecorator;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\StringTranslation\TranslationInterface; use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
...@@ -456,4 +457,37 @@ public function getEntityTypeLabels() { ...@@ -456,4 +457,37 @@ public function getEntityTypeLabels() {
return $options; return $options;
} }
/**
* {@inheritdoc}
*/
public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) {
$translation = $entity;
if ($entity instanceof TranslatableInterface) {
if (empty($langcode)) {
$langcode = $this->languageManager->getLanguage(Language::TYPE_CONTENT)->id;
}
// Retrieve language fallback candidates to perform the entity language
// negotiation.
$context['data'] = $entity;
$context += array('operation' => 'entity_view');
$candidates = $this->languageManager->getFallbackCandidates($langcode, $context);
// Ensure the default language has the proper language code.
$default_language = $entity->getUntranslated()->language();
$candidates[$default_language->id] = Language::LANGCODE_DEFAULT;
// Return the most fitting entity translation.
foreach ($candidates as $candidate) {
if ($entity->hasTranslation($candidate)) {
$translation = $entity->getTranslation($candidate);
break;
}
}
}
return $translation;
}
} }
...@@ -244,4 +244,27 @@ public function getForm(EntityInterface $entity, $operation = 'default', array $ ...@@ -244,4 +244,27 @@ public function getForm(EntityInterface $entity, $operation = 'default', array $
*/ */
public function getBundleInfo($entity_type); public function getBundleInfo($entity_type);
/**
* Returns 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.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity whose translation will be returned.
* @param string $langcode
* (optional) The language of the current context. Defaults to the current
* content language.
* @param array $context
* (optional) An associative array of arbitrary data that can be useful to
* determine the proper fallback sequence.
*
* @return \Drupal\Core\Entity\EntityInterface
* An entity object for the translated data.
*
* @see \Drupal\Core\Language\LanguageManager::getFallbackCandidates()
*/
public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array());
} }
...@@ -7,13 +7,15 @@ ...@@ -7,13 +7,15 @@
namespace Drupal\Core\Entity; namespace Drupal\Core\Entity;
use Drupal\entity\Entity\EntityDisplay; use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Language\Language; use Drupal\Core\Language\Language;
use Drupal\entity\Entity\EntityDisplay;
use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* Base class for entity view controllers. * Base class for entity view controllers.
*/ */
class EntityViewBuilder implements EntityViewBuilderInterface { class EntityViewBuilder implements EntityControllerInterface, EntityViewBuilderInterface {
/** /**
* The type of entities for which this controller is instantiated. * The type of entities for which this controller is instantiated.
...@@ -31,6 +33,13 @@ class EntityViewBuilder implements EntityViewBuilderInterface { ...@@ -31,6 +33,13 @@ class EntityViewBuilder implements EntityViewBuilderInterface {
*/ */
protected $entityInfo; protected $entityInfo;
/**
* The entity manager service.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/** /**
* An array of view mode info for the type of entities for which this * An array of view mode info for the type of entities for which this
* controller is instantiated. * controller is instantiated.
...@@ -49,12 +58,30 @@ class EntityViewBuilder implements EntityViewBuilderInterface { ...@@ -49,12 +58,30 @@ class EntityViewBuilder implements EntityViewBuilderInterface {
*/ */
protected $cacheBin = 'cache'; protected $cacheBin = 'cache';
public function __construct($entity_type) { /**
* Constructs a new EntityViewBuilder.
*
* @param string $entity_type
* The entity type.
* @param array $entity_info
* The entity information array.
* @param \Drupal\Core\Entity\EntityManager $entity_manager
* The entity manager service.
*/
public function __construct($entity_type, array $entity_info, EntityManager $entity_manager) {
$this->entityType = $entity_type; $this->entityType = $entity_type;
$this->entityInfo = entity_get_info($entity_type); $this->entityInfo = $entity_info;
$this->entityManager = $entity_manager;
$this->viewModesInfo = entity_get_view_modes($entity_type); $this->viewModesInfo = entity_get_view_modes($entity_type);
} }
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, $entity_type, array $entity_info) {
return new static($entity_type, $entity_info, $container->get('entity.manager'));
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
...@@ -167,9 +194,14 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la ...@@ -167,9 +194,14 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la
$view_modes = array(); $view_modes = array();
$displays = array(); $displays = array();
$context = array('langcode' => $langcode); $context = array('langcode' => $langcode);
foreach ($entities as $entity) { foreach ($entities as $key => $entity) {
$bundle = $entity->bundle(); $bundle = $entity->bundle();
// Ensure that from now on we are dealing with the proper translation
// object.
$entity = $this->entityManager->getTranslationFromContext($entity, $langcode);
$entities[$key] = $entity;
// Allow modules to change the view mode. // Allow modules to change the view mode.
$entity_view_mode = $view_mode; $entity_view_mode = $view_mode;
drupal_alter('entity_view_mode', $entity_view_mode, $entity, $context); drupal_alter('entity_view_mode', $entity_view_mode, $entity, $context);
......
...@@ -153,7 +153,7 @@ public function extend($obj) { ...@@ -153,7 +153,7 @@ public function extend($obj) {
* @param array $languages * @param array $languages
* The array of language objects keyed by langcode. * The array of language objects keyed by langcode.
*/ */
public static function sort($languages) { public static function sort(&$languages) {
uasort($languages, function ($a, $b) { uasort($languages, function ($a, $b) {
$a_weight = isset($a->weight) ? $a->weight : 0; $a_weight = isset($a->weight) ? $a->weight : 0;
$b_weight = isset($b->weight) ? $b->weight : 0; $b_weight = isset($b->weight) ? $b->weight : 0;
......
...@@ -7,8 +7,10 @@ ...@@ -7,8 +7,10 @@
namespace Drupal\Core\Language; namespace Drupal\Core\Language;
use Symfony\Component\HttpFoundation\Request; use Drupal\Component\Utility\MapArray;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface; use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Class responsible for initializing each language type. * Class responsible for initializing each language type.
...@@ -29,6 +31,13 @@ class LanguageManager { ...@@ -29,6 +31,13 @@ class LanguageManager {
*/ */
protected $state = NULL; protected $state = NULL;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/** /**
* An array of language objects keyed by language type. * An array of language objects keyed by language type.
* *
...@@ -57,10 +66,13 @@ class LanguageManager { ...@@ -57,10 +66,13 @@ class LanguageManager {
* Constructs an LanguageManager object. * Constructs an LanguageManager object.
* *
* @param \Drupal\Core\KeyValueStore\KeyValueStoreInterface $state * @param \Drupal\Core\KeyValueStore\KeyValueStoreInterface $state
* The state keyvalue store. * (optional) The state keyvalue store. Defaults to NULL.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* (optional) The module handler service. Defaults to NULL.
*/ */
public function __construct(KeyValueStoreInterface $state = NULL) { public function __construct(KeyValueStoreInterface $state = NULL, ModuleHandlerInterface $module_handler = NULL) {
$this->state = $state; $this->state = $state;
$this->moduleHandler = $module_handler;
} }
/** /**
...@@ -161,6 +173,53 @@ public function isMultilingual() { ...@@ -161,6 +173,53 @@ public function isMultilingual() {
return ($this->state->get('language_count') ?: 1) > 1; return ($this->state->get('language_count') ?: 1) > 1;
} }
/**
* Returns the language fallback candidates for a given context.
*
* @param string $langcode
* (optional) The language of the current context. Defaults to NULL.
* @param array $context
* (optional) An associative array of data that can be useful to determine
* the fallback sequence. The following keys are used in core:
* - langcode: The desired language.
* - operation: The name of the operation indicating the context where
* language fallback is being applied, e.g. 'entity_view'.
* - data: An arbitrary data structure that makes sense in the provided
* context, e.g. an entity.
*
* @return array
* An array of language codes sorted by priority: first values should be
* tried first.
*/
public function getFallbackCandidates($langcode = NULL, array $context = array()) {
if ($this->isMultilingual()) {
// Get languages ordered by weight, add Language::LANGCODE_NOT_SPECIFIED at
// the end.