function TwigSandboxTest::testEntitySafeMethods

Same name in other branches
  1. 9 core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php \Drupal\Tests\Core\Template\TwigSandboxTest::testEntitySafeMethods()
  2. 8.9.x core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php \Drupal\Tests\Core\Template\TwigSandboxTest::testEntitySafeMethods()
  3. 10 core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php \Drupal\Tests\Core\Template\TwigSandboxTest::testEntitySafeMethods()

Tests that valid methods can be called from within Twig templates.

Currently the following methods are in the allowed list: id, label, bundle, and get.

File

core/tests/Drupal/Tests/Core/Template/TwigSandboxTest.php, line 111

Class

TwigSandboxTest
Tests the twig sandbox policy.

Namespace

Drupal\Tests\Core\Template

Code

public function testEntitySafeMethods() : void {
    $entity = $this->getMockBuilder(ContentEntityBaseMockableClass::class)
        ->disableOriginalConstructor()
        ->getMock();
    $entity->expects($this->atLeastOnce())
        ->method('get')
        ->with('title')
        ->willReturn('test');
    $result = $this->twig
        ->render('{{ entity.get("title") }}', [
        'entity' => $entity,
    ]);
    $this->assertEquals('test', $result, 'Sandbox policy allows get() to be called.');
    $entity = $this->createMock('Drupal\\Core\\Entity\\EntityInterface');
    $entity->expects($this->atLeastOnce())
        ->method('id')
        ->willReturn('1234');
    $result = $this->twig
        ->render('{{ entity.id }}', [
        'entity' => $entity,
    ]);
    $this->assertEquals('1234', $result, 'Sandbox policy allows get() to be called.');
    $entity = $this->createMock('Drupal\\Core\\Entity\\EntityInterface');
    $entity->expects($this->atLeastOnce())
        ->method('label')
        ->willReturn('testing');
    $result = $this->twig
        ->render('{{ entity.label }}', [
        'entity' => $entity,
    ]);
    $this->assertEquals('testing', $result, 'Sandbox policy allows get() to be called.');
    $entity = $this->createMock('Drupal\\Core\\Entity\\EntityInterface');
    $entity->expects($this->atLeastOnce())
        ->method('bundle')
        ->willReturn('testing');
    $result = $this->twig
        ->render('{{ entity.bundle }}', [
        'entity' => $entity,
    ]);
    $this->assertEquals('testing', $result, 'Sandbox policy allows get() to be called.');
}

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