function AccessResultTest::testOrIfCacheabilityMerging

Same name and namespace in other branches
  1. 9 core/tests/Drupal/Tests/Core/Access/AccessResultTest.php \Drupal\Tests\Core\Access\AccessResultTest::testOrIfCacheabilityMerging()
  2. 10 core/tests/Drupal/Tests/Core/Access/AccessResultTest.php \Drupal\Tests\Core\Access\AccessResultTest::testOrIfCacheabilityMerging()
  3. 11.x core/tests/Drupal/Tests/Core/Access/AccessResultTest.php \Drupal\Tests\Core\Access\AccessResultTest::testOrIfCacheabilityMerging()

@covers ::orIf

Tests the special case of ORing non-forbidden access results that are both cacheable but have different cacheability metadata. This is only the case for non-forbidden access results; we still abort the ORing process as soon as a forbidden access result is encountered. This is tested in ::testOrIf().

File

core/tests/Drupal/Tests/Core/Access/AccessResultTest.php, line 887

Class

AccessResultTest
@coversDefaultClass <a href="/api/drupal/core%21lib%21Drupal%21Core%21Access%21AccessResult.php/class/AccessResult/8.9.x" title="Value object for passing an access result with cacheability metadata." class="local">\Drupal\Core\Access\AccessResult</a> @group Access

Namespace

Drupal\Tests\Core\Access

Code

public function testOrIfCacheabilityMerging() {
    $merge_both_directions = function (AccessResult $a, AccessResult $b) {
        // A globally cacheable access result.
        $a->setCacheMaxAge(3600);
        // Another access result that is cacheable per permissions.
        $b->setCacheMaxAge(86400)
            ->cachePerPermissions();
        $r1 = $a->orIf($b);
        $this->assertTrue($r1->getCacheMaxAge() === 3600);
        $this->assertSame([
            'user.permissions',
        ], $r1->getCacheContexts());
        $r2 = $b->orIf($a);
        $this->assertTrue($r2->getCacheMaxAge() === 3600);
        $this->assertSame([
            'user.permissions',
        ], $r2->getCacheContexts());
    };
    // Merge either direction, get the same result.
    $merge_both_directions(AccessResult::allowed(), AccessResult::allowed());
    $merge_both_directions(AccessResult::allowed(), AccessResult::neutral());
    $merge_both_directions(AccessResult::neutral(), AccessResult::neutral());
    $merge_both_directions(AccessResult::neutral(), AccessResult::allowed());
}

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