View source
<?php
namespace Drupal\Tests\media\Functional\FieldFormatter;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\media\Entity\Media;
use Drupal\Tests\media\Functional\MediaFunctionalTestBase;
use Drupal\Tests\TestFileCreationTrait;
class MediaThumbnailFormatterTest extends MediaFunctionalTestBase {
use TestFileCreationTrait;
protected $defaultTheme = 'stark';
public function testRender() {
$this
->drupalLogin($this->adminUser);
$node_storage = $this->container
->get('entity_type.manager')
->getStorage('node');
$this
->createMediaType('image', [
'id' => 'image',
]);
$this
->drupalCreateContentType([
'type' => 'article',
'name' => 'Article',
]);
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_media_reference',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => 1,
'settings' => [
'target_type' => 'media',
],
]);
$field_storage
->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'article',
'label' => 'Reference media',
'translatable' => FALSE,
])
->save();
$this->container
->get('entity_display.repository')
->getFormDisplay('node', 'article')
->setComponent('field_media_reference', [
'type' => 'entity_reference_autocomplete',
])
->save();
$this
->changeMediaReferenceFieldLinkType('media');
$file = File::create([
'uri' => current($this
->getTestFiles('image'))->uri,
]);
$file
->save();
$mediaImage = Media::create([
'bundle' => 'image',
'name' => 'Test image',
'field_media_image' => $file
->id(),
]);
$mediaImage
->save();
$title = $this
->randomMachineName();
$edit = [
'title[0][value]' => $title,
];
$edit['field_media_reference[0][target_id]'] = $mediaImage
->getName();
$this
->drupalGet('node/add/article');
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->responseContains('<a href="' . $mediaImage
->toUrl('edit-form')
->toString());
$node = $this
->drupalGetNodeByTitle($title);
$nid = $node
->id();
$this
->changeMediaReferenceFieldLinkType('content');
$node_storage
->resetCache([
$nid,
]);
$this
->drupalGet('node/' . $nid);
$this
->assertSession()
->responseContains('<a href="' . $node
->toUrl()
->toString());
}
private function changeMediaReferenceFieldLinkType(string $type) : void {
$this->container
->get('entity_display.repository')
->getViewDisplay('node', 'article', 'default')
->setComponent('field_media_reference', [
'type' => 'media_thumbnail',
'settings' => [
'image_link' => $type,
'image_style' => '',
],
])
->save();
}
}