You are here

public function EntityTranslationTest::testFieldDefinitions in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Entity/EntityTranslationTest.php \Drupal\KernelTests\Core\Entity\EntityTranslationTest::testFieldDefinitions()

Check that field translatability is handled properly.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityTranslationTest.php, line 674

Class

EntityTranslationTest
Tests entity translation functionality.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testFieldDefinitions() {

  // Check that field translatability can be altered to be enabled or disabled
  // in field definitions.
  $entity_type = 'entity_test_mulrev';
  $this->state
    ->set('entity_test.field_definitions.translatable', [
    'name' => FALSE,
  ]);
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $entity_field_manager
    ->clearCachedFieldDefinitions();
  $definitions = $entity_field_manager
    ->getBaseFieldDefinitions($entity_type);
  $this
    ->assertFalse($definitions['name']
    ->isTranslatable(), 'Field translatability can be disabled programmatically.');
  $this->state
    ->set('entity_test.field_definitions.translatable', [
    'name' => TRUE,
  ]);
  $entity_field_manager
    ->clearCachedFieldDefinitions();
  $definitions = $entity_field_manager
    ->getBaseFieldDefinitions($entity_type);
  $this
    ->assertTrue($definitions['name']
    ->isTranslatable(), 'Field translatability can be enabled programmatically.');

  // Check that field translatability is disabled by default.
  $base_field_definitions = EntityTestMulRev::baseFieldDefinitions($this->entityTypeManager
    ->getDefinition($entity_type));
  $this
    ->assertTrue(!isset($base_field_definitions['id']->translatable), 'Translatability for the <em>id</em> field is not defined.');
  $this
    ->assertFalse($definitions['id']
    ->isTranslatable(), 'Field translatability is disabled by default.');

  // Check that entity id keys have the expect translatability.
  $translatable_fields = [
    'id' => TRUE,
    'uuid' => TRUE,
    'revision_id' => TRUE,
    'type' => TRUE,
    'langcode' => FALSE,
  ];
  foreach ($translatable_fields as $name => $translatable) {
    $this->state
      ->set('entity_test.field_definitions.translatable', [
      $name => $translatable,
    ]);
    $entity_field_manager
      ->clearCachedFieldDefinitions();
    try {
      $entity_field_manager
        ->getBaseFieldDefinitions($entity_type);
      $this
        ->fail("Field {$name} cannot be translatable.");
    } catch (\LogicException $e) {

      // Expected exception; just continue testing.
    }
  }
}