function StringFormatterTest::testLinkToEntity

Checks link visibility depending on link templates and access.

@phpstan-param class-string<\Drupal\Core\Access\AccessResultInterface>|null $accessClass

@dataProvider providerAccessLinkToEntity

Parameters

bool $hasUrl: Whether the entity type has a canonical link template.

string|null $accessClass: The access result for the current user.

bool $expectIsLinkElement: Whether to expect the text to be wrapped in a link element.

File

core/modules/field/tests/src/Unit/Plugin/Field/FieldFormatter/StringFormatterTest.php, line 42

Class

StringFormatterTest
Tests the string field formatter.

Namespace

Drupal\Tests\field\Unit\Plugin\Field\FieldFormatter

Code

public function testLinkToEntity(bool $hasUrl, ?string $accessClass, bool $expectIsLinkElement) : void {
    $fieldDefinition = $this->prophesize(FieldDefinitionInterface::class);
    $entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class);
    $fieldFormatter = new StringFormatter('foobar', [], $fieldDefinition->reveal(), [], 'TestLabel', 'default', [], $entityTypeManager->reveal());
    $fieldFormatter->setSetting('link_to_entity', TRUE);
    $entityType = $this->prophesize(EntityTypeInterface::class);
    $entityType->hasLinkTemplate('canonical')
        ->willReturn($hasUrl)
        ->shouldBeCalledTimes(1);
    $entityType->hasLinkTemplate('revision')
        ->willReturn(FALSE)
        ->shouldBeCalledTimes($hasUrl ? 1 : 0);
    $entity = $this->prophesize(EntityInterface::class);
    $entity->isNew()
        ->willReturn(FALSE);
    $entity->getEntityType()
        ->willReturn($entityType->reveal());
    if ($hasUrl) {
        $url = $this->prophesize(Url::class);
        $url->access(NULL, TRUE)
            ->willReturn(new $accessClass());
        $entity->toUrl('canonical')
            ->willReturn($url);
    }
    $item = $this->getMockBuilder(StringItem::class)
        ->disableOriginalConstructor()
        ->onlyMethods([])
        ->getMock();
    $item->setValue([
        'value' => 'FooText',
    ]);
    $items = $this->prophesize(FieldItemListInterface::class);
    $items->getEntity()
        ->willReturn($entity->reveal());
    $items->valid()
        ->willReturn(TRUE, FALSE);
    $items->next();
    $items->rewind();
    $items->current()
        ->willReturn($item);
    $items->key()
        ->willReturn(0);
    $elements = $fieldFormatter->viewElements($items->reveal(), 'en');
    if ($expectIsLinkElement) {
        $this->assertEquals('link', $elements[0]['#type']);
        $this->assertEquals('FooText', $elements[0]['#title']['#context']['value']);
    }
    else {
        $this->assertEquals('inline_template', $elements[0]['#type']);
        $this->assertEquals('FooText', $elements[0]['#context']['value']);
    }
}

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