3 namespace Drupal\KernelTests\Core\Entity;
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\Core\Language\LanguageInterface;
7 use Drupal\Core\TypedData\TranslationStatusInterface;
8 use Drupal\entity_test\Entity\EntityTestMulRev;
9 use Drupal\field\Entity\FieldConfig;
10 use Drupal\field\Entity\FieldStorageConfig;
11 use Drupal\language\Entity\ConfigurableLanguage;
14 * Tests entity translation functionality.
18 class EntityTranslationTest extends EntityLanguageTestBase {
21 * Tests language related methods of the Entity class.
23 public function testEntityLanguageMethods() {
24 // All entity variations have to have the same results.
25 foreach (entity_test_entity_types() as $entity_type) {
26 $this->doTestEntityLanguageMethods($entity_type);
31 * Executes the entity language method tests for the given entity type.
33 * @param string $entity_type
34 * The entity type to run the tests with.
36 protected function doTestEntityLanguageMethods($entity_type) {
37 $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
38 $entity = $this->container->get('entity_type.manager')
39 ->getStorage($entity_type)
42 'user_id' => $this->container->get('current_user')->id(),
44 $this->assertEqual($entity->language()->getId(), $this->languageManager->getDefaultLanguage()->getId(), format_string('%entity_type: Entity created with API has default language.', ['%entity_type' => $entity_type]));
45 $entity = $this->container->get('entity_type.manager')
46 ->getStorage($entity_type)
49 'user_id' => \Drupal::currentUser()->id(),
50 $langcode_key => LanguageInterface::LANGCODE_NOT_SPECIFIED,
53 $this->assertEqual($entity->language()->getId(), LanguageInterface::LANGCODE_NOT_SPECIFIED, format_string('%entity_type: Entity language not specified.', ['%entity_type' => $entity_type]));
54 $this->assertFalse($entity->getTranslationLanguages(FALSE), format_string('%entity_type: No translations are available', ['%entity_type' => $entity_type]));
56 // Set the value in default language.
57 $entity->set($this->fieldName, [0 => ['value' => 'default value']]);
59 $field = $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT)->get($this->fieldName);
60 $this->assertEqual($field->value, 'default value', format_string('%entity_type: Untranslated value retrieved.', ['%entity_type' => $entity_type]));
61 $this->assertEqual($field->getLangcode(), LanguageInterface::LANGCODE_NOT_SPECIFIED, format_string('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));
63 // Try to get add a translation to language neutral entity.
64 $message = 'Adding a translation to a language-neutral entity results in an error.';
66 $entity->addTranslation($this->langcodes[1]);
67 $this->fail($message);
69 catch (\InvalidArgumentException $e) {
70 $this->pass($message);
73 // Now, make the entity language-specific by assigning a language and test
75 $default_langcode = $this->langcodes[0];
76 $entity->{$langcode_key}->value = $default_langcode;
77 $entity->{$this->fieldName} = [];
78 $this->assertEqual($entity->language(), \Drupal::languageManager()->getLanguage($this->langcodes[0]), format_string('%entity_type: Entity language retrieved.', ['%entity_type' => $entity_type]));
79 $this->assertFalse($entity->getTranslationLanguages(FALSE), format_string('%entity_type: No translations are available', ['%entity_type' => $entity_type]));
81 // Set the value in default language.
82 $entity->set($this->fieldName, [0 => ['value' => 'default value']]);
84 $field = $entity->get($this->fieldName);
85 $this->assertEqual($field->value, 'default value', format_string('%entity_type: Untranslated value retrieved.', ['%entity_type' => $entity_type]));
86 $this->assertEqual($field->getLangcode(), $default_langcode, format_string('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));
89 $entity->addTranslation($this->langcodes[1])->set($this->fieldName, [0 => ['value' => 'translation 1']]);
90 $field = $entity->getTranslation($this->langcodes[1])->{$this->fieldName};
91 $this->assertEqual($field->value, 'translation 1', format_string('%entity_type: Translated value set.', ['%entity_type' => $entity_type]));
92 $this->assertEqual($field->getLangcode(), $this->langcodes[1], format_string('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));
94 // Make sure the untranslated value stays.
95 $field = $entity->get($this->fieldName);
96 $this->assertEqual($field->value, 'default value', 'Untranslated value stays.');
97 $this->assertEqual($field->getLangcode(), $default_langcode, 'Untranslated value has the expected langcode.');
99 $translations[$this->langcodes[1]] = \Drupal::languageManager()->getLanguage($this->langcodes[1]);
100 $this->assertEqual($entity->getTranslationLanguages(FALSE), $translations, 'Translations retrieved.');
102 // Try to get a value using a language code for a non-existing translation.
103 $message = 'Getting a non existing translation results in an error.';
105 $entity->getTranslation($this->langcodes[2])->get($this->fieldName)->value;
106 $this->fail($message);
108 catch (\InvalidArgumentException $e) {
109 $this->pass($message);
112 // Try to get a not available translation.
113 $this->assertNull($entity->addTranslation($this->langcodes[2])->get($this->fieldName)->value, format_string('%entity_type: A translation that is not available is NULL.', ['%entity_type' => $entity_type]));
115 // Try to get a value using an invalid language code.
116 $message = 'Getting an invalid translation results in an error.';
118 $entity->getTranslation('invalid')->get($this->fieldName)->value;
119 $this->fail($message);
121 catch (\InvalidArgumentException $e) {
122 $this->pass($message);
125 // Try to set a value using an invalid language code.
127 $entity->getTranslation('invalid')->set($this->fieldName, NULL);
128 $this->fail(format_string('%entity_type: Setting a translation for an invalid language throws an exception.', ['%entity_type' => $entity_type]));
130 catch (\InvalidArgumentException $e) {
131 $this->pass(format_string('%entity_type: Setting a translation for an invalid language throws an exception.', ['%entity_type' => $entity_type]));
134 // Set the value in default language.
135 $field_name = 'field_test_text';
136 $entity->getTranslation($this->langcodes[1])->set($field_name, [0 => ['value' => 'default value2']]);
138 $field = $entity->get($field_name);
139 $this->assertEqual($field->value, 'default value2', format_string('%entity_type: Untranslated value set into a translation in non-strict mode.', ['%entity_type' => $entity_type]));
140 $this->assertEqual($field->getLangcode(), $default_langcode, format_string('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));
144 * Tests multilingual properties.
146 public function testMultilingualProperties() {
147 // Test all entity variations with data table support.
148 foreach (entity_test_entity_types(ENTITY_TEST_TYPES_MULTILINGUAL) as $entity_type) {
149 $this->doTestMultilingualProperties($entity_type);
154 * Executes the multilingual property tests for the given entity type.
156 * @param string $entity_type
157 * The entity type to run the tests with.
159 protected function doTestMultilingualProperties($entity_type) {
160 $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
161 $default_langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('default_langcode');
162 $name = $this->randomMachineName();
163 $uid = mt_rand(0, 127);
164 $langcode = $this->langcodes[0];
166 // Create a language neutral entity and check that properties are stored
167 // as language neutral.
168 $storage = $this->container->get('entity_type.manager')
169 ->getStorage($entity_type);
170 $entity = $storage->create(['name' => $name, 'user_id' => $uid, $langcode_key => LanguageInterface::LANGCODE_NOT_SPECIFIED]);
172 $entity = $storage->load($entity->id());
173 $default_langcode = $entity->language()->getId();
174 $this->assertEqual($default_langcode, LanguageInterface::LANGCODE_NOT_SPECIFIED, format_string('%entity_type: Entity created as language neutral.', ['%entity_type' => $entity_type]));
175 $field = $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT)->get('name');
176 $this->assertEqual($name, $field->value, format_string('%entity_type: The entity name has been correctly stored as language neutral.', ['%entity_type' => $entity_type]));
177 $this->assertEqual($default_langcode, $field->getLangcode(), format_string('%entity_type: The field object has the expect langcode.', ['%entity_type' => $entity_type]));
178 $this->assertEqual($uid, $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored as language neutral.', ['%entity_type' => $entity_type]));
180 $translation = $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
181 $field = $translation->get('name');
182 $this->assertEqual($name, $field->value, format_string('%entity_type: The entity name defaults to neutral language.', ['%entity_type' => $entity_type]));
183 $this->assertEqual($default_langcode, $field->getLangcode(), format_string('%entity_type: The field object has the expect langcode.', ['%entity_type' => $entity_type]));
184 $this->assertEqual($uid, $translation->get('user_id')->target_id, format_string('%entity_type: The entity author defaults to neutral language.', ['%entity_type' => $entity_type]));
185 $field = $entity->get('name');
186 $this->assertEqual($name, $field->value, format_string('%entity_type: The entity name can be retrieved without specifying a language.', ['%entity_type' => $entity_type]));
187 $this->assertEqual($default_langcode, $field->getLangcode(), format_string('%entity_type: The field object has the expect langcode.', ['%entity_type' => $entity_type]));
188 $this->assertEqual($uid, $entity->get('user_id')->target_id, format_string('%entity_type: The entity author can be retrieved without specifying a language.', ['%entity_type' => $entity_type]));
190 // Create a language-aware entity and check that properties are stored
191 // as language-aware.
192 $entity = $this->container->get('entity_type.manager')
193 ->getStorage($entity_type)
194 ->create(['name' => $name, 'user_id' => $uid, $langcode_key => $langcode]);
196 $entity = $storage->load($entity->id());
197 $default_langcode = $entity->language()->getId();
198 $this->assertEqual($default_langcode, $langcode, format_string('%entity_type: Entity created as language specific.', ['%entity_type' => $entity_type]));
199 $field = $entity->getTranslation($langcode)->get('name');
200 $this->assertEqual($name, $field->value, format_string('%entity_type: The entity name has been correctly stored as a language-aware property.', ['%entity_type' => $entity_type]));
201 $this->assertEqual($default_langcode, $field->getLangcode(), format_string('%entity_type: The field object has the expect langcode.', ['%entity_type' => $entity_type]));
202 $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored as a language-aware property.', ['%entity_type' => $entity_type]));
204 // Create property translations.
206 $default_langcode = $langcode;
207 foreach ($this->langcodes as $langcode) {
208 if ($langcode != $default_langcode) {
209 $properties[$langcode] = [
210 'name' => [0 => $this->randomMachineName()],
211 'user_id' => [0 => mt_rand(128, 256)],
215 $properties[$langcode] = [
216 'name' => [0 => $name],
217 'user_id' => [0 => $uid],
220 $translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
221 foreach ($properties[$langcode] as $field_name => $values) {
222 $translation->set($field_name, $values);
227 // Check that property translation were correctly stored.
228 $entity = $storage->load($entity->id());
229 foreach ($this->langcodes as $langcode) {
231 '%entity_type' => $entity_type,
232 '%langcode' => $langcode,
234 $field = $entity->getTranslation($langcode)->get('name');
235 $this->assertEqual($properties[$langcode]['name'][0], $field->value, format_string('%entity_type: The entity name has been correctly stored for language %langcode.', $args));
236 $field_langcode = ($langcode == $entity->language()->getId()) ? $default_langcode : $langcode;
237 $this->assertEqual($field_langcode, $field->getLangcode(), format_string('%entity_type: The field object has the expected langcode %langcode.', $args));
238 $this->assertEqual($properties[$langcode]['user_id'][0], $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('%entity_type: The entity author has been correctly stored for language %langcode.', $args));
241 // Test query conditions (cache is reset at each call).
242 $translated_id = $entity->id();
243 // Create an additional entity with only the uid set. The uid for the
244 // original language is the same of one used for a translation.
245 $langcode = $this->langcodes[1];
246 /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
247 $storage = $this->container->get('entity_type.manager')
248 ->getStorage($entity_type);
250 'user_id' => $properties[$langcode]['user_id'],
251 'name' => 'some name',
252 $langcode_key => LanguageInterface::LANGCODE_NOT_SPECIFIED,
256 $entities = $storage->loadMultiple();
257 $this->assertEqual(count($entities), 3, format_string('%entity_type: Three entities were created.', ['%entity_type' => $entity_type]));
258 $entities = $storage->loadMultiple([$translated_id]);
259 $this->assertEqual(count($entities), 1, format_string('%entity_type: One entity correctly loaded by id.', ['%entity_type' => $entity_type]));
260 $entities = $storage->loadByProperties(['name' => $name]);
261 $this->assertEqual(count($entities), 2, format_string('%entity_type: Two entities correctly loaded by name.', ['%entity_type' => $entity_type]));
262 // @todo The default language condition should go away in favor of an
263 // explicit parameter.
264 $entities = $storage->loadByProperties(['name' => $properties[$langcode]['name'][0], $default_langcode_key => 0]);
265 $this->assertEqual(count($entities), 1, format_string('%entity_type: One entity correctly loaded by name translation.', ['%entity_type' => $entity_type]));
266 $entities = $storage->loadByProperties([$langcode_key => $default_langcode, 'name' => $name]);
267 $this->assertEqual(count($entities), 1, format_string('%entity_type: One entity correctly loaded by name and language.', ['%entity_type' => $entity_type]));
269 $entities = $storage->loadByProperties([$langcode_key => $langcode, 'name' => $properties[$langcode]['name'][0]]);
270 $this->assertEqual(count($entities), 0, format_string('%entity_type: No entity loaded by name translation specifying the translation language.', ['%entity_type' => $entity_type]));
271 $entities = $storage->loadByProperties([$langcode_key => $langcode, 'name' => $properties[$langcode]['name'][0], $default_langcode_key => 0]);
272 $this->assertEqual(count($entities), 1, format_string('%entity_type: One entity loaded by name translation and language specifying to look for translations.', ['%entity_type' => $entity_type]));
273 $entities = $storage->loadByProperties(['user_id' => $properties[$langcode]['user_id'][0], $default_langcode_key => NULL]);
274 $this->assertEqual(count($entities), 2, format_string('%entity_type: Two entities loaded by uid without caring about property translatability.', ['%entity_type' => $entity_type]));
276 // Test property conditions and orders with multiple languages in the same
278 $query = \Drupal::entityQuery($entity_type);
279 $group = $query->andConditionGroup()
280 ->condition('user_id', $properties[$default_langcode]['user_id'][0], '=', $default_langcode)
281 ->condition('name', $properties[$default_langcode]['name'][0], '=', $default_langcode);
284 ->condition('name', $properties[$langcode]['name'][0], '=', $langcode)
286 $this->assertEqual(count($result), 1, format_string('%entity_type: One entity loaded by name and uid using different language meta conditions.', ['%entity_type' => $entity_type]));
288 // Test mixed property and field conditions.
289 $storage->resetCache($result);
290 $entity = $storage->load(reset($result));
291 $field_value = $this->randomString();
292 $entity->getTranslation($langcode)->set($this->fieldName, [['value' => $field_value]]);
294 $query = \Drupal::entityQuery($entity_type);
295 $default_langcode_group = $query->andConditionGroup()
296 ->condition('user_id', $properties[$default_langcode]['user_id'][0], '=', $default_langcode)
297 ->condition('name', $properties[$default_langcode]['name'][0], '=', $default_langcode);
298 $langcode_group = $query->andConditionGroup()
299 ->condition('name', $properties[$langcode]['name'][0], '=', $langcode)
300 ->condition("$this->fieldName.value", $field_value, '=', $langcode);
302 ->condition($langcode_key, $default_langcode)
303 ->condition($default_langcode_group)
304 ->condition($langcode_group)
306 $this->assertEqual(count($result), 1, format_string('%entity_type: One entity loaded by name, uid and field value using different language meta conditions.', ['%entity_type' => $entity_type]));
310 * Tests the Entity Translation API behavior.
312 public function testEntityTranslationAPI() {
313 // Test all entity variations with data table support.
314 foreach (entity_test_entity_types(ENTITY_TEST_TYPES_MULTILINGUAL) as $entity_type) {
315 $this->doTestEntityTranslationAPI($entity_type);
320 * Executes the Entity Translation API tests for the given entity type.
322 * @param string $entity_type
323 * The entity type to run the tests with.
325 protected function doTestEntityTranslationAPI($entity_type) {
326 $default_langcode = $this->langcodes[0];
327 $langcode = $this->langcodes[1];
328 $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
329 $default_langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('default_langcode');
331 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
332 $entity = $this->entityManager
333 ->getStorage($entity_type)
334 ->create(['name' => $this->randomMachineName(), $langcode_key => LanguageInterface::LANGCODE_NOT_SPECIFIED]);
337 $hooks = $this->getHooksInfo();
338 $this->assertFalse($hooks, 'No entity translation hooks are fired when creating an entity.');
340 // Verify that we obtain the entity object itself when we attempt to
341 // retrieve a translation referring to it.
342 $translation = $entity->getTranslation(LanguageInterface::LANGCODE_NOT_SPECIFIED);
343 $this->assertFalse($translation->isNewTranslation(), 'Existing translations are not marked as new.');
344 $this->assertSame($entity, $translation, 'The translation object corresponding to a non-default language is the entity object itself when the entity is language-neutral.');
345 $entity->{$langcode_key}->value = $default_langcode;
346 $translation = $entity->getTranslation($default_langcode);
347 $this->assertSame($entity, $translation, 'The translation object corresponding to the default language (explicit) is the entity object itself.');
348 $translation = $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT);
349 $this->assertSame($entity, $translation, 'The translation object corresponding to the default language (implicit) is the entity object itself.');
350 $this->assertTrue($entity->{$default_langcode_key}->value, 'The translation object is the default one.');
352 // Verify that trying to retrieve a translation for a locked language when
353 // the entity is language-aware causes an exception to be thrown.
354 $message = 'A language-neutral translation cannot be retrieved.';
356 $entity->getTranslation(LanguageInterface::LANGCODE_NOT_SPECIFIED);
357 $this->fail($message);
359 catch (\LogicException $e) {
360 $this->pass($message);
363 // Create a translation and verify that the translation object and the
364 // original object behave independently.
365 $name = $default_langcode . '_' . $this->randomMachineName();
366 $entity->name->value = $name;
367 $name_translated = $langcode . '_' . $this->randomMachineName();
368 $translation = $entity->addTranslation($langcode);
369 $this->assertTrue($translation->isNewTranslation(), 'Newly added translations are marked as new.');
370 $this->assertNotIdentical($entity, $translation, 'The entity and the translation object differ from one another.');
371 $this->assertTrue($entity->hasTranslation($langcode), 'The new translation exists.');
372 $this->assertEqual($translation->language()->getId(), $langcode, 'The translation language matches the specified one.');
373 $this->assertEqual($translation->{$langcode_key}->value, $langcode, 'The translation field language value matches the specified one.');
374 $this->assertFalse($translation->{$default_langcode_key}->value, 'The translation object is not the default one.');
375 $this->assertEqual($translation->getUntranslated()->language()->getId(), $default_langcode, 'The original language can still be retrieved.');
376 $translation->name->value = $name_translated;
377 $this->assertEqual($entity->name->value, $name, 'The original name is retained after setting a translated value.');
378 $entity->name->value = $name;
379 $this->assertEqual($translation->name->value, $name_translated, 'The translated name is retained after setting the original value.');
381 // Save the translation and check that the expected hooks are fired.
382 $translation->save();
383 $hooks = $this->getHooksInfo();
385 $this->assertEqual($hooks['entity_translation_create'], $langcode, 'The generic entity translation creation hook has fired.');
386 $this->assertEqual($hooks[$entity_type . '_translation_create'], $langcode, 'The entity-type-specific entity translation creation hook has fired.');
388 $this->assertEqual($hooks['entity_translation_insert'], $langcode, 'The generic entity translation insertion hook has fired.');
389 $this->assertEqual($hooks[$entity_type . '_translation_insert'], $langcode, 'The entity-type-specific entity translation insertion hook has fired.');
391 // Verify that changing translation language causes an exception to be
393 $message = 'The translation language cannot be changed.';
395 $translation->{$langcode_key}->value = $this->langcodes[2];
396 $this->fail($message);
398 catch (\LogicException $e) {
399 $this->pass($message);
402 // Verify that reassigning the same translation language is allowed.
403 $message = 'The translation language can be reassigned the same value.';
405 $translation->{$langcode_key}->value = $langcode;
406 $this->pass($message);
408 catch (\LogicException $e) {
409 $this->fail($message);
412 // Verify that changing the default translation flag causes an exception to
414 foreach ($entity->getTranslationLanguages() as $t_langcode => $language) {
415 $translation = $entity->getTranslation($t_langcode);
416 $default = $translation->isDefaultTranslation();
418 $message = 'The default translation flag can be reassigned the same value.';
420 $translation->{$default_langcode_key}->value = $default;
421 $this->pass($message);
423 catch (\LogicException $e) {
424 $this->fail($message);
427 $message = 'The default translation flag cannot be changed.';
429 $translation->{$default_langcode_key}->value = !$default;
430 $this->fail($message);
432 catch (\LogicException $e) {
433 $this->pass($message);
436 $this->assertEqual($translation->{$default_langcode_key}->value, $default);
439 // Check that after loading an entity the language is the default one.
440 $entity = $this->reloadEntity($entity);
441 $this->assertEqual($entity->language()->getId(), $default_langcode, 'The loaded entity is the original one.');
443 // Add another translation and check that everything works as expected. A
444 // new translation object can be obtained also by just specifying a valid
446 $langcode2 = $this->langcodes[2];
447 $translation = $entity->addTranslation($langcode2);
448 $value = $entity !== $translation && $translation->language()->getId() == $langcode2 && $entity->hasTranslation($langcode2);
449 $this->assertTrue($value, 'A new translation object can be obtained also by specifying a valid language.');
450 $this->assertEqual($entity->language()->getId(), $default_langcode, 'The original language has been preserved.');
451 $translation->save();
452 $hooks = $this->getHooksInfo();
454 $this->assertEqual($hooks['entity_translation_create'], $langcode2, 'The generic entity translation creation hook has fired.');
455 $this->assertEqual($hooks[$entity_type . '_translation_create'], $langcode2, 'The entity-type-specific entity translation creation hook has fired.');
457 $this->assertEqual($hooks['entity_translation_insert'], $langcode2, 'The generic entity translation insertion hook has fired.');
458 $this->assertEqual($hooks[$entity_type . '_translation_insert'], $langcode2, 'The entity-type-specific entity translation insertion hook has fired.');
460 // Verify that trying to manipulate a translation object referring to a
461 // removed translation results in exceptions being thrown.
462 $entity = $this->reloadEntity($entity);
463 $translation = $entity->getTranslation($langcode2);
464 $entity->removeTranslation($langcode2);
465 foreach (['get', 'set', '__get', '__set', 'createDuplicate'] as $method) {
466 $message = format_string('The @method method raises an exception when trying to manipulate a removed translation.', ['@method' => $method]);
468 $translation->{$method}('name', $this->randomMachineName());
469 $this->fail($message);
471 catch (\Exception $e) {
472 $this->pass($message);
476 // Verify that deletion hooks are fired when saving an entity with a removed
479 $hooks = $this->getHooksInfo();
480 $this->assertEqual($hooks['entity_translation_delete'], $langcode2, 'The generic entity translation deletion hook has fired.');
481 $this->assertEqual($hooks[$entity_type . '_translation_delete'], $langcode2, 'The entity-type-specific entity translation deletion hook has fired.');
482 $entity = $this->reloadEntity($entity);
483 $this->assertFalse($entity->hasTranslation($langcode2), 'The translation does not appear among available translations after saving the entity.');
485 // Check that removing an invalid translation causes an exception to be
487 foreach ([$default_langcode, LanguageInterface::LANGCODE_DEFAULT, $this->randomMachineName()] as $invalid_langcode) {
488 $message = format_string('Removing an invalid translation (@langcode) causes an exception to be thrown.', ['@langcode' => $invalid_langcode]);
490 $entity->removeTranslation($invalid_langcode);
491 $this->fail($message);
493 catch (\Exception $e) {
494 $this->pass($message);
498 // Check that hooks are fired only when actually storing data.
499 $entity = $this->reloadEntity($entity);
500 $entity->addTranslation($langcode2);
501 $entity->removeTranslation($langcode2);
503 $hooks = $this->getHooksInfo();
505 $this->assertTrue(isset($hooks['entity_translation_create']), 'The generic entity translation creation hook is run when adding and removing a translation without storing it.');
506 unset($hooks['entity_translation_create']);
507 $this->assertTrue(isset($hooks[$entity_type . '_translation_create']), 'The entity-type-specific entity translation creation hook is run when adding and removing a translation without storing it.');
508 unset($hooks[$entity_type . '_translation_create']);
510 $this->assertFalse($hooks, 'No other hooks beyond the entity translation creation hooks are run when adding and removing a translation without storing it.');
512 // Check that hooks are fired only when actually storing data.
513 $entity = $this->reloadEntity($entity);
514 $entity->addTranslation($langcode2);
516 $entity = $this->reloadEntity($entity);
517 $this->assertTrue($entity->hasTranslation($langcode2), 'Entity has translation after adding one and saving.');
518 $entity->removeTranslation($langcode2);
520 $entity = $this->reloadEntity($entity);
521 $this->assertFalse($entity->hasTranslation($langcode2), 'Entity does not have translation after removing it and saving.');
522 // Reset hook firing information.
523 $this->getHooksInfo();
525 // Verify that entity serialization does not cause stale references to be
527 $entity = $this->reloadEntity($entity);
528 $translation = $entity->getTranslation($langcode);
529 $entity = unserialize(serialize($entity));
530 $entity->name->value = $this->randomMachineName();
531 $name = $default_langcode . '_' . $this->randomMachineName();
532 $entity->getTranslation($default_langcode)->name->value = $name;
533 $this->assertEqual($entity->name->value, $name, 'No stale reference for the translation object corresponding to the original language.');
534 $translation2 = $entity->getTranslation($langcode);
535 $translation2->name->value .= $this->randomMachineName();
536 $this->assertNotEqual($translation->name->value, $translation2->name->value, 'No stale reference for the actual translation object.');
537 $this->assertEqual($entity, $translation2->getUntranslated(), 'No stale reference in the actual translation object.');
539 // Verify that deep-cloning is still available when we are not instantiating
540 // a translation object, which instead relies on shallow cloning.
541 $entity = $this->reloadEntity($entity);
542 $entity->getTranslation($langcode);
543 $cloned = clone $entity;
544 $translation = $cloned->getTranslation($langcode);
545 $this->assertNotIdentical($entity, $translation->getUntranslated(), 'A cloned entity object has no reference to the original one.');
546 $entity->removeTranslation($langcode);
547 $this->assertFalse($entity->hasTranslation($langcode));
548 $this->assertTrue($cloned->hasTranslation($langcode));
550 // Check that untranslatable field references keep working after serializing
551 // and cloning the entity.
552 $entity = $this->reloadEntity($entity);
553 $type = $this->randomMachineName();
554 $entity->getTranslation($langcode)->type->value = $type;
555 $entity = unserialize(serialize($entity));
556 $cloned = clone $entity;
557 $translation = $cloned->getTranslation($langcode);
558 $translation->type->value = strrev($type);
559 $this->assertEqual($cloned->type->value, $translation->type->value, 'Untranslatable field references keep working after serializing and cloning the entity.');
561 // Check that per-language defaults are properly populated. The
562 // 'entity_test_mul_default_value' entity type is translatable and uses
563 // entity_test_field_default_value() as a "default value callback" for its
564 // 'description' field.
565 $entity = $this->entityManager
566 ->getStorage('entity_test_mul_default_value')
567 ->create(['name' => $this->randomMachineName(), 'langcode' => $langcode]);
568 $translation = $entity->addTranslation($langcode2);
571 'shape' => "shape:0:description_$langcode2",
572 'color' => "color:0:description_$langcode2",
575 'shape' => "shape:1:description_$langcode2",
576 'color' => "color:1:description_$langcode2",
579 $this->assertEqual($translation->description->getValue(), $expected, 'Language-aware default values correctly populated.');
580 $this->assertEqual($translation->description->getLangcode(), $langcode2, 'Field object has the expected langcode.');
582 // Reset hook firing information.
583 $this->getHooksInfo();
587 * Tests language fallback applied to field and entity translations.
589 public function testLanguageFallback() {
590 // Test all entity variations with data table support.
591 foreach (entity_test_entity_types(ENTITY_TEST_TYPES_MULTILINGUAL) as $entity_type) {
592 $this->doTestLanguageFallback($entity_type);
597 * Executes the language fallback test for the given entity type.
599 * @param string $entity_type
600 * The entity type to run the tests with.
602 protected function doTestLanguageFallback($entity_type) {
603 /** @var \Drupal\Core\Render\RendererInterface $renderer */
604 $renderer = $this->container->get('renderer');
606 $current_langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
607 $this->langcodes[] = $current_langcode;
610 foreach ($this->langcodes as $langcode) {
611 $values[$langcode]['name'] = $this->randomMachineName();
612 $values[$langcode]['user_id'] = mt_rand(0, 127);
615 $default_langcode = $this->langcodes[0];
616 $langcode = $this->langcodes[1];
617 $langcode2 = $this->langcodes[2];
618 $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
619 $languages = $this->languageManager->getLanguages();
620 $language = ConfigurableLanguage::load($languages[$langcode]->getId());
621 $language->set('weight', 1);
623 $this->languageManager->reset();
625 $controller = $this->entityManager->getStorage($entity_type);
626 $entity = $controller->create([$langcode_key => $default_langcode] + $values[$default_langcode]);
629 $entity->addTranslation($langcode, $values[$langcode]);
632 // Check that retrieving the current translation works as expected.
633 $entity = $this->reloadEntity($entity);
634 $translation = $this->entityManager->getTranslationFromContext($entity, $langcode2);
635 $this->assertEqual($translation->language()->getId(), $default_langcode, 'The current translation language matches the expected one.');
637 // Check that language fallback respects language weight by default.
638 $language = ConfigurableLanguage::load($languages[$langcode]->getId());
639 $language->set('weight', -1);
641 $translation = $this->entityManager->getTranslationFromContext($entity, $langcode2);
642 $this->assertEqual($translation->language()->getId(), $langcode, 'The current translation language matches the expected one.');
644 // Check that the current translation is properly returned.
645 $translation = $this->entityManager->getTranslationFromContext($entity);
646 $this->assertEqual($langcode, $translation->language()->getId(), 'The current translation language matches the topmost language fallback candidate.');
647 $entity->addTranslation($current_langcode, $values[$current_langcode]);
648 $translation = $this->entityManager->getTranslationFromContext($entity);
649 $this->assertEqual($current_langcode, $translation->language()->getId(), 'The current translation language matches the current language.');
651 // Check that if the entity has no translation no fallback is applied.
652 $entity2 = $controller->create([$langcode_key => $default_langcode]);
653 // Get an view builder.
654 $controller = $this->entityManager->getViewBuilder($entity_type);
655 $entity2_build = $controller->view($entity2);
656 $entity2_output = (string) $renderer->renderRoot($entity2_build);
657 $translation = $this->entityManager->getTranslationFromContext($entity2, $default_langcode);
658 $translation_build = $controller->view($translation);
659 $translation_output = (string) $renderer->renderRoot($translation_build);
660 $this->assertSame($entity2_output, $translation_output, 'When the entity has no translation no fallback is applied.');
662 // Checks that entity translations are rendered properly.
663 $controller = $this->entityManager->getViewBuilder($entity_type);
664 $build = $controller->view($entity);
665 $renderer->renderRoot($build);
666 $this->assertEqual($build['label']['#markup'], $values[$current_langcode]['name'], 'By default the entity is rendered in the current language.');
668 $langcodes = array_combine($this->langcodes, $this->langcodes);
669 // We have no translation for the $langcode2 language, hence the expected
670 // result is the topmost existing translation, that is $langcode.
671 $langcodes[$langcode2] = $langcode;
672 foreach ($langcodes as $desired => $expected) {
673 $build = $controller->view($entity, 'full', $desired);
674 // Unset the #cache key so that a fresh render is produced with each pass,
675 // making the renderable array keys available to compare.
676 unset($build['#cache']);
677 $renderer->renderRoot($build);
678 $this->assertEqual($build['label']['#markup'], $values[$expected]['name'], 'The entity is rendered in the expected language.');
683 * Check that field translatability is handled properly.
685 public function testFieldDefinitions() {
686 // Check that field translatability can be altered to be enabled or disabled
687 // in field definitions.
688 $entity_type = 'entity_test_mulrev';
689 $this->state->set('entity_test.field_definitions.translatable', ['name' => FALSE]);
690 $this->entityManager->clearCachedFieldDefinitions();
691 $definitions = $this->entityManager->getBaseFieldDefinitions($entity_type);
692 $this->assertFalse($definitions['name']->isTranslatable(), 'Field translatability can be disabled programmatically.');
694 $this->state->set('entity_test.field_definitions.translatable', ['name' => TRUE]);
695 $this->entityManager->clearCachedFieldDefinitions();
696 $definitions = $this->entityManager->getBaseFieldDefinitions($entity_type);
697 $this->assertTrue($definitions['name']->isTranslatable(), 'Field translatability can be enabled programmatically.');
699 // Check that field translatability is disabled by default.
700 $base_field_definitions = EntityTestMulRev::baseFieldDefinitions($this->entityManager->getDefinition($entity_type));
701 $this->assertTrue(!isset($base_field_definitions['id']->translatable), 'Translatability for the <em>id</em> field is not defined.');
702 $this->assertFalse($definitions['id']->isTranslatable(), 'Field translatability is disabled by default.');
704 // Check that entity id keys have the expect translatability.
705 $translatable_fields = [
708 'revision_id' => TRUE,
712 foreach ($translatable_fields as $name => $translatable) {
713 $this->state->set('entity_test.field_definitions.translatable', [$name => $translatable]);
714 $this->entityManager->clearCachedFieldDefinitions();
715 $message = format_string('Field %field cannot be translatable.', ['%field' => $name]);
718 $this->entityManager->getBaseFieldDefinitions($entity_type);
719 $this->fail($message);
721 catch (\LogicException $e) {
722 $this->pass($message);
728 * Tests that changing entity language does not break field language.
730 public function testLanguageChange() {
731 // Test all entity variations with data table support.
732 foreach (entity_test_entity_types(ENTITY_TEST_TYPES_MULTILINGUAL) as $entity_type) {
733 $this->doTestLanguageChange($entity_type);
738 * Executes the entity language change test for the given entity type.
740 * @param string $entity_type
741 * The entity type to run the tests with.
743 protected function doTestLanguageChange($entity_type) {
744 $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
745 $controller = $this->entityManager->getStorage($entity_type);
746 $langcode = $this->langcodes[0];
748 // check that field languages match entity language regardless of field
751 $langcode_key => $langcode,
752 $this->fieldName => $this->randomMachineName(),
753 $this->untranslatableFieldName => $this->randomMachineName(),
755 $entity = $controller->create($values);
756 foreach ([$this->fieldName, $this->untranslatableFieldName] as $field_name) {
757 $this->assertEqual($entity->get($field_name)->getLangcode(), $langcode, 'Field language works as expected.');
760 // Check that field languages keep matching entity language even after
762 $langcode = $this->langcodes[1];
763 $entity->{$langcode_key}->value = $langcode;
764 foreach ([$this->fieldName, $this->untranslatableFieldName] as $field_name) {
765 $this->assertEqual($entity->get($field_name)->getLangcode(), $langcode, 'Field language works as expected after changing entity language.');
768 // Check that entity translation does not affect the language of original
769 // field values and untranslatable ones.
770 $langcode = $this->langcodes[0];
771 $entity->addTranslation($this->langcodes[2], [$this->fieldName => $this->randomMachineName()]);
772 $entity->{$langcode_key}->value = $langcode;
773 foreach ([$this->fieldName, $this->untranslatableFieldName] as $field_name) {
774 $this->assertEqual($entity->get($field_name)->getLangcode(), $langcode, 'Field language works as expected after translating the entity and changing language.');
777 // Check that setting the default language to an existing translation
778 // language causes an exception to be thrown.
779 $message = 'An exception is thrown when setting the default language to an existing translation language';
781 $entity->{$langcode_key}->value = $this->langcodes[2];
782 $this->fail($message);
784 catch (\InvalidArgumentException $e) {
785 $this->pass($message);
790 * Tests how entity adapters work with translations.
792 public function testEntityAdapter() {
793 $entity_type = 'entity_test';
794 $default_langcode = 'en';
795 $values[$default_langcode] = ['name' => $this->randomString()];
796 $controller = $this->entityManager->getStorage($entity_type);
797 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
798 $entity = $controller->create($values[$default_langcode]);
800 foreach ($this->langcodes as $langcode) {
801 $values[$langcode] = ['name' => $this->randomString()];
802 $entity->addTranslation($langcode, $values[$langcode]);
805 $langcodes = array_merge([$default_langcode], $this->langcodes);
806 foreach ($langcodes as $langcode) {
807 $adapter = $entity->getTranslation($langcode)->getTypedData();
808 $name = $adapter->get('name')->value;
809 $this->assertEqual($name, $values[$langcode]['name'], SafeMarkup::format('Name correctly retrieved from "@langcode" adapter', ['@langcode' => $langcode]));
814 * Tests if entity references are correct after adding a new translation.
816 public function testFieldEntityReference() {
817 $entity_type = 'entity_test_mul';
818 $controller = $this->entityManager->getStorage($entity_type);
819 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
820 $entity = $controller->create();
822 foreach ($this->langcodes as $langcode) {
823 $entity->addTranslation($langcode);
826 $default_langcode = $entity->getUntranslated()->language()->getId();
827 foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
828 $translation = $entity->getTranslation($langcode);
829 foreach ($translation->getFields() as $field_name => $field) {
830 if ($field->getFieldDefinition()->isTranslatable()) {
831 $args = ['%field_name' => $field_name, '%langcode' => $langcode];
832 $this->assertEqual($langcode, $field->getEntity()->language()->getId(), format_string('Translatable field %field_name on translation %langcode has correct entity reference in translation %langcode.', $args));
835 $args = ['%field_name' => $field_name, '%langcode' => $langcode, '%default_langcode' => $default_langcode];
836 $this->assertEqual($default_langcode, $field->getEntity()->language()->getId(), format_string('Non translatable field %field_name on translation %langcode has correct entity reference in the default translation %default_langcode.', $args));
843 * Tests if entity translation statuses are correct after removing two
846 public function testDeleteEntityTranslation() {
847 $entity_type = 'entity_test_mul';
848 $controller = $this->entityManager->getStorage($entity_type);
850 // Create a translatable test field.
851 $field_storage = FieldStorageConfig::create([
852 'entity_type' => $entity_type,
853 'field_name' => 'translatable_test_field',
854 'type' => 'field_test',
856 $field_storage->save();
858 $field = FieldConfig::create([
859 'field_storage' => $field_storage,
860 'label' => $this->randomMachineName(),
861 'bundle' => $entity_type,
865 // Create an untranslatable test field.
866 $field_storage = FieldStorageConfig::create([
867 'entity_type' => $entity_type,
868 'field_name' => 'untranslatable_test_field',
869 'type' => 'field_test',
870 'translatable' => FALSE,
872 $field_storage->save();
874 $field = FieldConfig::create([
875 'field_storage' => $field_storage,
876 'label' => $this->randomMachineName(),
877 'bundle' => $entity_type,
881 // Create an entity with both translatable and untranslatable test fields.
883 'name' => $this->randomString(),
884 'translatable_test_field' => $this->randomString(),
885 'untranslatable_test_field' => $this->randomString(),
888 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
889 $entity = $controller->create($values);
891 foreach ($this->langcodes as $langcode) {
892 $entity->addTranslation($langcode, $values);
896 // Assert there are no deleted languages in the lists yet.
897 $this->assertNull(\Drupal::state()->get('entity_test.delete.translatable_test_field'));
898 $this->assertNull(\Drupal::state()->get('entity_test.delete.untranslatable_test_field'));
900 // Remove the second and third langcodes from the entity.
901 $entity->removeTranslation('l1');
902 $entity->removeTranslation('l2');
905 // Ensure that for the translatable test field the second and third
906 // langcodes are in the deleted languages list.
907 $actual = \Drupal::state()->get('entity_test.delete.translatable_test_field');
908 $expected_translatable = ['l1', 'l2'];
910 sort($expected_translatable);
911 $this->assertEqual($actual, $expected_translatable);
912 // Ensure that the untranslatable test field is untouched.
913 $this->assertNull(\Drupal::state()->get('entity_test.delete.untranslatable_test_field'));
915 // Delete the entity, which removes all remaining translations.
918 // All languages have been deleted now.
919 $actual = \Drupal::state()->get('entity_test.delete.translatable_test_field');
920 $expected_translatable[] = 'en';
921 $expected_translatable[] = 'l0';
923 sort($expected_translatable);
924 $this->assertEqual($actual, $expected_translatable);
926 // The untranslatable field is shared and only deleted once, for the
928 $actual = \Drupal::state()->get('entity_test.delete.untranslatable_test_field');
929 $expected_untranslatable = ['en'];
931 sort($expected_untranslatable);
932 $this->assertEqual($actual, $expected_untranslatable);
936 * Tests the getTranslationStatus method.
938 public function testTranslationStatus() {
939 $entity_type = 'entity_test_mul';
940 $storage = $this->entityManager->getStorage($entity_type);
942 // Create an entity with both translatable and untranslatable test fields.
944 'name' => $this->randomString(),
945 'translatable_test_field' => $this->randomString(),
946 'untranslatable_test_field' => $this->randomString(),
949 /** @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\TypedData\TranslationStatusInterface $entity */
950 // Test that newly created entity has the translation status
951 // TRANSLATION_CREATED.
952 $entity = $storage->create($values);
953 $this->assertEquals(TranslationStatusInterface::TRANSLATION_CREATED, $entity->getTranslationStatus($entity->language()->getId()));
955 // Test that after saving a newly created entity it has the translation
956 // status TRANSLATION_EXISTING.
958 $this->assertEquals(TranslationStatusInterface::TRANSLATION_EXISTING, $entity->getTranslationStatus($entity->language()->getId()));
960 // Test that after loading an existing entity it has the translation status
961 // TRANSLATION_EXISTING.
962 $storage->resetCache();
963 $entity = $storage->load($entity->id());
964 $this->assertEquals(TranslationStatusInterface::TRANSLATION_EXISTING, $entity->getTranslationStatus($entity->language()->getId()));
966 foreach ($this->langcodes as $key => $langcode) {
967 // Test that after adding a new translation it has the translation status
968 // TRANSLATION_CREATED.
969 $entity->addTranslation($langcode, $values);
970 $this->assertEquals(TranslationStatusInterface::TRANSLATION_CREATED, $entity->getTranslationStatus($langcode));
972 // Test that after removing a newly added and not yet saved translation
973 // it does not have any translation status for the removed translation.
974 $entity->removeTranslation($langcode);
975 $this->assertEquals(NULL, $entity->getTranslationStatus($langcode));
977 // Test that after adding a new translation and saving the entity it has
978 // the translation status TRANSLATION_EXISTING.
979 $entity->addTranslation($langcode, $values)
981 $this->assertEquals(TranslationStatusInterface::TRANSLATION_EXISTING, $entity->getTranslationStatus($langcode));
983 // Test that after removing an existing translation its translation
984 // status has changed to TRANSLATION_REMOVED.
985 $entity->removeTranslation($langcode);
986 $this->assertEquals(TranslationStatusInterface::TRANSLATION_REMOVED, $entity->getTranslationStatus($langcode));
988 // Test that after removing an existing translation and adding it again
989 // its translation status has changed back to TRANSLATION_EXISTING.
990 $entity->addTranslation($langcode, $values);
991 $this->assertEquals(TranslationStatusInterface::TRANSLATION_EXISTING, $entity->getTranslationStatus($langcode));
993 // Test that after removing an existing translation and saving the entity
994 // it does not have any translation status for the removed translation.
995 $entity->removeTranslation($langcode);
997 $this->assertEquals(NULL, $entity->getTranslationStatus($langcode));
999 // Tests that after removing an existing translation, saving the entity,
1000 // adding the translation again, the translation status of this
1001 // translation is TRANSLATION_CREATED.
1002 $entity->addTranslation($langcode, $values);
1003 $this->assertEquals(TranslationStatusInterface::TRANSLATION_CREATED, $entity->getTranslationStatus($langcode));
1007 // Test that after loading an existing entity it has the translation status
1008 // TRANSLATION_EXISTING for all of its translations.
1009 $storage->resetCache();
1010 $entity = $storage->load($entity->id());
1011 foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
1012 $this->assertEquals(TranslationStatusInterface::TRANSLATION_EXISTING, $entity->getTranslationStatus($langcode));