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:
arguments: ['@event_dispatcher', '@service_container', '@controller_resolver']
language_manager:
class: Drupal\Core\Language\LanguageManager
arguments: ['@state']
arguments: ['@state', '@module_handler']
string_translator.custom_strings:
class: Drupal\Core\StringTranslation\Translator\CustomStrings
arguments: ['@settings']
......
......@@ -545,30 +545,6 @@ function language_url_split_prefix($path, $languages) {
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"
*/
......@@ -423,6 +423,12 @@ protected function getTranslatedField($property_name, $langcode) {
*/
public function set($property_name, $value, $notify = TRUE) {
$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) {
$translation->values = &$this->values;
$translation->fields = &$this->fields;
$translation->translations = &$this->translations;
$translation->enforceIsNew = &$this->enforceIsNew;
$translation->translationInitialize = FALSE;
return $translation;
......
......@@ -8,6 +8,7 @@
namespace Drupal\Core\Entity;
use Drupal\Core\Language\Language;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Entity form controller variant for content entity types.
......@@ -16,6 +17,32 @@
*/
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}
*/
......@@ -38,6 +65,7 @@ public function form(array $form, array &$form_state) {
* {@inheritdoc}
*/
public function validate(array $form, array &$form_state) {
$this->updateFormLangcode($form_state);
$entity = $this->buildEntity($form, $form_state);
$entity_type = $entity->entityType();
$entity_langcode = $entity->language()->id;
......@@ -73,53 +101,22 @@ public function validate(array $form, array &$form_state) {
protected function init(array &$form_state) {
// Ensure we act on the translation object corresponding to the current form
// 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);
$translation = $this->entity->getTranslation($langcode);
// Ensure that the entity object is a BC entity if the original one is.
return $this->entity instanceof EntityBCDecorator ? $translation->getBCEntity() : $translation;
$this->entity = $this->entity->getTranslation($langcode);
parent::init($form_state);
}
/**
* {@inheritdoc}
*/
public function getFormLangcode(array $form_state) {
$entity = $this->entity;
if (!empty($form_state['langcode'])) {
$langcode = $form_state['langcode'];
}
else {
// 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;
public function getFormLangcode(array &$form_state) {
if (empty($form_state['langcode'])) {
// Imply a 'view' operation to ensure users edit entities in the same
// language they are displayed. This allows to keep contextual editing
// working also for multilingual entities.
$form_state['langcode'] = $this->entityManager->getTranslationFromContext($this->entity)->language()->id;
}
return $form_state['langcode'];
}
/**
......@@ -136,8 +133,8 @@ public function buildEntity(array $form, array &$form_state) {
$entity = clone $this->entity;
$entity_type = $entity->entityType();
$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
// field API without changing existing entity fields that are not being
// 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) {
}
return $entity;
}
}
......@@ -269,6 +269,7 @@ protected function actions(array $form, array &$form_state) {
* {@inheritdoc}
*/
public function validate(array $form, array &$form_state) {
$this->updateFormLangcode($form_state);
// @todo Remove this.
// Execute legacy global validation handlers.
unset($form_state['validate_handlers']);
......@@ -292,8 +293,6 @@ public function validate(array $form, array &$form_state) {
public function submit(array $form, array &$form_state) {
// Remove button and internal Form API values from submitted values.
form_state_values_clean($form_state);
$this->updateFormLangcode($form_state);
$this->entity = $this->buildEntity($form, $form_state);
return $this->entity;
}
......@@ -325,7 +324,7 @@ public function delete(array $form, array &$form_state) {
/**
* {@inheritdoc}
*/
public function getFormLangcode(array $form_state) {
public function getFormLangcode(array &$form_state) {
return $this->entity->language()->id;
}
......
......@@ -26,7 +26,7 @@ interface EntityFormControllerInterface extends BaseFormIdInterface {
* @return string
* 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.
......
......@@ -91,7 +91,7 @@ public function bundle();
*
* @param $langcode
* (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.
*
* @return
......
......@@ -10,6 +10,7 @@
use Drupal\Component\Plugin\PluginManagerBase;
use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManager;
use Drupal\Core\Language\Language;
......@@ -17,8 +18,8 @@
use Drupal\Core\Plugin\Discovery\CacheDecorator;
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
use Drupal\Core\Plugin\Discovery\InfoHookDecorator;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
......@@ -456,4 +457,37 @@ public function getEntityTypeLabels() {
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 $
*/
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 @@
namespace Drupal\Core\Entity;
use Drupal\entity\Entity\EntityDisplay;
use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Language\Language;
use Drupal\entity\Entity\EntityDisplay;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* 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.
......@@ -31,6 +33,13 @@ class EntityViewBuilder implements EntityViewBuilderInterface {
*/
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
* controller is instantiated.
......@@ -49,12 +58,30 @@ class EntityViewBuilder implements EntityViewBuilderInterface {
*/
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->entityInfo = entity_get_info($entity_type);
$this->entityInfo = $entity_info;
$this->entityManager = $entity_manager;
$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}
*/
......@@ -167,9 +194,14 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la
$view_modes = array();
$displays = array();
$context = array('langcode' => $langcode);
foreach ($entities as $entity) {
foreach ($entities as $key => $entity) {
$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.
$entity_view_mode = $view_mode;
drupal_alter('entity_view_mode', $entity_view_mode, $entity, $context);
......
......@@ -153,7 +153,7 @@ public function extend($obj) {
* @param array $languages
* The array of language objects keyed by langcode.
*/
public static function sort($languages) {
public static function sort(&$languages) {
uasort($languages, function ($a, $b) {
$a_weight = isset($a->weight) ? $a->weight : 0;
$b_weight = isset($b->weight) ? $b->weight : 0;
......
......@@ -7,8 +7,10 @@
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 Symfony\Component\HttpFoundation\Request;
/**
* Class responsible for initializing each language type.
......@@ -29,6 +31,13 @@ class LanguageManager {
*/
protected $state = NULL;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* An array of language objects keyed by language type.
*
......@@ -57,10 +66,13 @@ class LanguageManager {
* Constructs an LanguageManager object.
*
* @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->moduleHandler = $module_handler;
}
/**
......@@ -161,6 +173,53 @@ public function isMultilingual() {
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.
$candidates = array_keys(language_list());
$candidates[] = Language::LANGCODE_NOT_SPECIFIED;
$candidates = MapArray::copyValuesToKeys($candidates);
// The first candidate should always be the desired language if specified.
if (!empty($langcode)) {
$candidates = array($langcode => $langcode) + $candidates;
}
// Let other modules hook in and add/change candidates.
$type = 'language_fallback_candidates';
$types = array();
if (!empty($context['operation'])) {
$types[] = $type . '_' . $context['operation'];
}
$types[] = $type;
$this->moduleHandler->alter($types, $candidates, $context);
}
else {
$candidates = array(Language::LANGCODE_DEFAULT);
}
return $candidates;
}
/**
* Returns an array of the available language types.
*
......
......@@ -7,6 +7,8 @@
namespace Drupal\Core\TypedData;
use Drupal\Core\Language\LanguageManager;
/**
* Interface for translatable data.
*/
......@@ -35,10 +37,9 @@ public function getTranslationLanguages($include_default = TRUE);
/**
* Gets a translation of the data.
*
* The returned translation has to be implement the same typed data interfaces
* as this typed data object, excluding the TranslatableInterface. E.g., if
* this typed data object implements the ComplexDataInterface and
* AccessibleInterface, the translation object has to implement both as well.
* The returned translation has to be of the same type than this typed data
* object. If the specified translation does not exist, a new one will be
* instantiated.
*
* @param $langcode
* The language code of the translation to get or Language::LANGCODE_DEFAULT
......@@ -49,7 +50,6 @@ public function getTranslationLanguages($include_default = TRUE);
*/
public function getTranslation($langcode);
/**
* Returns the translatable object referring to the original language.
*
......
......@@ -9,7 +9,7 @@
use Drupal\Component\Utility\String;
use Drupal\Core\Entity\ContentEntityFormController;
use Drupal\Core\Entity\EntityStorageControllerInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Language\Language;
use Drupal\aggregator\CategoryStorageControllerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -19,13 +19,6 @@
*/
class FeedFormController extends ContentEntityFormController {
/**
* The feed storage.
*
* @var \Drupal\Core\Entity\EntityStorageControllerInterface
*/
protected $feedStorageController;
/**
* The category storage controller.
*
......@@ -36,13 +29,13 @@ class FeedFormController extends ContentEntityFormController {
/**
* Constructs a FeedForm object.
*
* @param \Drupal\Core\Entity\EntityStorageControllerInterface $feed_storage
* The feed storage.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\aggregator\CategoryStorageControllerInterface $category_storage_controller
* The category storage controller.
*/
public function __construct(EntityStorageControllerInterface $feed_storage, CategoryStorageControllerInterface $category_storage_controller) {
$this->feedStorageController = $feed_storage;
public function __construct(EntityManagerInterface $entity_manager, CategoryStorageControllerInterface $category_storage_controller) {
parent::__construct($entity_manager);
$this->categoryStorageController = $category_storage_controller;
}
......@@ -51,7 +44,7 @@ public function __construct(EntityStorageControllerInterface $feed_storage, Cate
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.entity')->getStorageController('aggregator_feed'),
$container->get('entity.manager'),
$container->get('aggregator.category.storage')
);
}
......@@ -125,7 +118,8 @@ public function form(array $form, array &$form_state) {
public function validate(array $form, array &$form_state) {
$feed = $this->buildEntity($form, $form_state);
// Check for duplicate titles.
$result = $this->feedStorageController->getFeedDuplicates($feed);
$feed_storage_controller = $this->entityManager->getStorageController('aggregator_feed');
$result = $feed_storage_controller->getFeedDuplicates($feed);
foreach ($result as $item) {
if (strcasecmp($item->title, $feed->label()) == 0) {
form_set_error('title', $this->t('A feed named %feed already exists. Enter a unique title.', array('%feed' => $feed->label())));
......
......@@ -8,6 +8,7 @@
namespace Drupal\book\Form;
use Drupal\Core\Entity\ContentEntityFormController;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\book\BookManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -32,19 +33,25 @@ class BookOutlineForm extends ContentEntityFormController {
/**
* Constructs a BookOutlineForm object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\book\BookManager $book_manager
* The BookManager service.
*/
public function __construct(BookManager $bookManager) {
$this->bookManager = $bookManager;
public function __construct(EntityManagerInterface $entity_manager, BookManager $book_manager) {
parent::__construct($entity_manager);
$this->bookManager = $book_manager;
}
/**
* This method lets us inject the services this class needs.
*
* Only inject services that are actually needed. Which services
* are needed will vary by the controller.
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('book.manager'));
return new static(
$container->get('entity.manager'),
$container->get('book.manager')
);
}
/**
......
......@@ -896,7 +896,7 @@ function comment_translation_configuration_element_submit($form, &$form_state) {
$key = 'language_configuration';
$comment_form_state = array(
'content_translation' => array('key' => $key),
'language' => array($key => array('entity_type' => 'comment', 'bundle' => $form['#field']['name'])),
'language' => array($key => array('entity_type' => 'comment', 'bundle' => $form['#field']->name)),
'values' => array($key => array('content_translation' => $form_state['values']['content_translation'])),
);
content_translation_language_configuration_element_submit($form, $comment_form_state);
......
......@@ -23,13 +23,6 @@
*/
class CommentFormController extends ContentEntityFormController {
/**
* The entity manager service.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* The field info service.
*
......@@ -58,13 +51,28 @@ public static function create(ContainerInterface $container) {
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(EntityManagerInterface $entity_manager, FieldInfo $field_info, AccountInterface $current_user) {
$this->entityManager = $entity_manager;
parent::__construct($entity_manager);
$this->fieldInfo = $field_info;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
protected function init(array &$form_state) {
$comment = $this->entity;
// Make the comment inherit the current content language unless specifically
// set.
if ($comment->isNew()) {
$language_content = \Drupal::languageManager()->getLanguage(Language::TYPE_CONTENT);
$comment->langcode->value = $language_content->id;
}
parent::init($form_state);
}
/**
* Overrides Drupal\Core\Entity\EntityFormController::form().
*/
......@@ -207,13 +215,6 @@ public function form(array $form, array &$form_state) {
'#value' => ($comment->id() ? !$comment->uid->target_id : $this->currentUser->isAnonymous()),
);
// Make the comment inherit the current content language unless specifically
// set.
if ($comment->isNew()) {
$language_content = language(Language::TYPE_CONTENT);
$comment->langcode->value = $language_content->id;
}
// Add internal comment properties.
$original = $comment->getUntranslated();
foreach (array('cid', 'pid', 'entity_id', 'entity_type', 'field_id', 'uid', 'langcode') as $key) {
......