function UsageTest::testFileUsageWithEntityTranslation

Same name and namespace in other branches
  1. 9 core/modules/file/tests/src/Kernel/UsageTest.php \Drupal\Tests\file\Kernel\UsageTest::testFileUsageWithEntityTranslation()
  2. 8.9.x core/modules/file/tests/src/Kernel/UsageTest.php \Drupal\Tests\file\Kernel\UsageTest::testFileUsageWithEntityTranslation()
  3. 11.x core/modules/file/tests/src/Kernel/UsageTest.php \Drupal\Tests\file\Kernel\UsageTest::testFileUsageWithEntityTranslation()

Tests file usage with translated entities.

File

core/modules/file/tests/src/Kernel/UsageTest.php, line 251

Class

UsageTest
Tests file usage functions.

Namespace

Drupal\Tests\file\Kernel

Code

public function testFileUsageWithEntityTranslation() : void {
  /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
  $file_usage = $this->container
    ->get('file.usage');
  $this->enableModules([
    'node',
    'language',
  ]);
  $this->installEntitySchema('node');
  $this->installSchema('node', [
    'node_access',
  ]);
  ConfigurableLanguage::create([
    'id' => 'en',
    'label' => 'English',
  ])->save();
  ConfigurableLanguage::create([
    'id' => 'ro',
    'label' => 'Romanian',
  ])->save();
  NodeType::create([
    'type' => 'page',
    'name' => 'Page',
  ])->save();
  ContentLanguageSettings::loadByEntityTypeBundle('node', 'page')->setLanguageAlterable(FALSE)
    ->setDefaultLangcode('en')
    ->save();
  // Create a file field attached to 'page' node-type.
  FieldStorageConfig::create([
    'type' => 'file',
    'entity_type' => 'node',
    'field_name' => 'file',
  ])->save();
  FieldConfig::create([
    'entity_type' => 'node',
    'bundle' => 'page',
    'field_name' => 'file',
    'label' => 'File',
  ])->save();
  // Create a node, attach a file and add a Romanian translation.
  $node = Node::create([
    'type' => 'page',
    'title' => 'Page',
  ]);
  $node->set('file', $file = $this->createFile())
    ->addTranslation('ro', $node->getTranslation('en')
    ->toArray())
    ->save();
  // Check that the file is used twice.
  $usage = $file_usage->listUsage($file);
  $this->assertEquals(2, $usage['file']['node'][$node->id()]);
  // Remove the Romanian translation.
  $node->removeTranslation('ro');
  $node->save();
  // Check that one usage has been removed and is used only once now.
  $usage = $file_usage->listUsage($file);
  $this->assertEquals(1, $usage['file']['node'][$node->id()]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.