View source
<?php
namespace Drupal\KernelTests\Core\Cache;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\user\Entity\Role;
class CacheContextOptimizationTest extends KernelTestBase {
use UserCreationTrait;
protected static $modules = [
'user',
'system',
];
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('user');
$this
->installConfig([
'user',
]);
$this
->installSchema('system', [
'sequences',
]);
}
public function testUserPermissionCacheContextOptimization() {
$user1 = $this
->createUser();
$this
->assertEquals(1, $user1
->id());
$authenticated_user = $this
->createUser([
'administer permissions',
]);
$role = $authenticated_user
->getRoles()[1];
$test_element = [
'#cache' => [
'keys' => [
'test',
],
'contexts' => [
'user',
'user.permissions',
],
],
];
\Drupal::service('account_switcher')
->switchTo($authenticated_user);
$element = $test_element;
$element['#markup'] = 'content for authenticated users';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('content for authenticated users', $output);
$element = $test_element;
$element['#markup'] = 'this should not be visible';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('content for authenticated users', $output);
Role::load($role)
->revokePermission('administer permissions')
->save();
$element = $test_element;
$element['#markup'] = 'this should be visible';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('this should be visible', $output);
}
public function testUserRolesCacheContextOptimization() {
$root_user = $this
->createUser();
$this
->assertEquals(1, $root_user
->id());
$authenticated_user = $this
->createUser([
'administer permissions',
]);
$role = $authenticated_user
->getRoles()[1];
$test_element = [
'#cache' => [
'keys' => [
'test',
],
'contexts' => [
'user',
'user.roles',
],
],
];
\Drupal::service('account_switcher')
->switchTo($authenticated_user);
$element = $test_element;
$element['#markup'] = 'content for authenticated users';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('content for authenticated users', $output);
$element = $test_element;
$element['#markup'] = 'this should not be visible';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('content for authenticated users', $output);
$authenticated_user
->removeRole($role);
$authenticated_user
->save();
$element = $test_element;
$element['#markup'] = 'this should be visible';
$output = \Drupal::service('renderer')
->renderRoot($element);
$this
->assertEquals('this should be visible', $output);
}
}