function TwigEnvironmentTest::testTemplateInvalidation

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Theme/TwigEnvironmentTest.php \Drupal\KernelTests\Core\Theme\TwigEnvironmentTest::testTemplateInvalidation()
  2. 10 core/tests/Drupal/KernelTests/Core/Theme/TwigEnvironmentTest.php \Drupal\KernelTests\Core\Theme\TwigEnvironmentTest::testTemplateInvalidation()
  3. 11.x core/tests/Drupal/KernelTests/Core/Theme/TwigEnvironmentTest.php \Drupal\KernelTests\Core\Theme\TwigEnvironmentTest::testTemplateInvalidation()

Test template invalidation.

File

core/tests/Drupal/KernelTests/Core/Theme/TwigEnvironmentTest.php, line 194

Class

TwigEnvironmentTest
Tests the twig environment.

Namespace

Drupal\KernelTests\Core\Theme

Code

public function testTemplateInvalidation() {
    $template_before = <<<TWIG
<div>Hello before</div>
TWIG;
    $template_after = <<<TWIG
<div>Hello after</div>
TWIG;
    $tempfile = tempnam(sys_get_temp_dir(), '__METHOD__') . '.html.twig';
    file_put_contents($tempfile, $template_before);
    
    /** @var \Drupal\Core\Template\TwigEnvironment $environment */
    $environment = \Drupal::service('twig');
    $output = $environment->load(basename($tempfile))
        ->render();
    $this->assertEquals($template_before, $output);
    file_put_contents($tempfile, $template_after);
    $output = $environment->load(basename($tempfile))
        ->render();
    $this->assertEquals($template_before, $output);
    $environment->invalidate();
    // Manually change $templateClassPrefix to force a different template
    // classname, as the other class is still loaded. This wouldn't be a problem
    // on a real site where you reload the page.
    $reflection = new \ReflectionClass(\Twig_Environment::class);
    $property_reflection = $reflection->getProperty('templateClassPrefix');
    $property_reflection->setAccessible(TRUE);
    $property_reflection->setValue($environment, 'otherPrefix');
    $output = $environment->load(basename($tempfile))
        ->render();
    $this->assertEquals($template_after, $output);
}

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