function CacheableMetadataCalculationTest::testCacheableMetadataCalculation

Same name in other branches
  1. 9 core/modules/views/tests/src/Kernel/CacheableMetadataCalculationTest.php \Drupal\Tests\views\Kernel\CacheableMetadataCalculationTest::testCacheableMetadataCalculation()
  2. 8.9.x core/modules/views/tests/src/Kernel/CacheableMetadataCalculationTest.php \Drupal\Tests\views\Kernel\CacheableMetadataCalculationTest::testCacheableMetadataCalculation()
  3. 11.x core/modules/views/tests/src/Kernel/CacheableMetadataCalculationTest.php \Drupal\Tests\views\Kernel\CacheableMetadataCalculationTest::testCacheableMetadataCalculation()

Tests that cacheability metadata is only calculated when needed.

Determining the cacheability of a view is an expensive operation since it requires all Views plugins and handlers to be initialized. For efficiency reasons this should only be done if a view is being saved (either through the UI or the API). The cacheability metadata is then stored in the view config and is ready to use at runtime.

It should not be calculated when a view is enabled through installing a module, or by syncing configuration.

See also

\Drupal\views\Entity\View::addCacheMetadata()

File

core/modules/views/tests/src/Kernel/CacheableMetadataCalculationTest.php, line 72

Class

CacheableMetadataCalculationTest
Tests that cacheability metadata is only calculated when needed.

Namespace

Drupal\Tests\views\Kernel

Code

public function testCacheableMetadataCalculation() : void {
    // Enabling a module that contains a view should not cause the cacheability
    // metadata to be recalculated.
    $this->enableModules([
        self::TEST_MODULE,
    ]);
    $this->installConfig([
        self::TEST_MODULE,
    ]);
    $this->assertCacheableMetadataHasBeenCalculated(FALSE);
    // When a view is saved normally we have to recalculate the cacheability
    // metadata, since it is possible changes have been made to the view that
    // affect cacheability.
    $view = $this->entityTypeManager
        ->getStorage('view')
        ->load(self::TEST_VIEW_ID);
    $view->save();
    $this->assertCacheableMetadataHasBeenCalculated(TRUE);
    $this->resetState();
    // When a view is being saved due to config being synchronized, the
    // cacheability metadata doesn't change so it should not be recalculated.
    $view->setSyncing(TRUE);
    $view->save();
    $this->assertCacheableMetadataHasBeenCalculated(FALSE);
}

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