function DynamicPageCacheSubscriber::onRequest

Same name in other branches
  1. 9 core/modules/dynamic_page_cache/src/EventSubscriber/DynamicPageCacheSubscriber.php \Drupal\dynamic_page_cache\EventSubscriber\DynamicPageCacheSubscriber::onRequest()
  2. 8.9.x core/modules/dynamic_page_cache/src/EventSubscriber/DynamicPageCacheSubscriber.php \Drupal\dynamic_page_cache\EventSubscriber\DynamicPageCacheSubscriber::onRequest()
  3. 11.x core/modules/dynamic_page_cache/src/EventSubscriber/DynamicPageCacheSubscriber.php \Drupal\dynamic_page_cache\EventSubscriber\DynamicPageCacheSubscriber::onRequest()

Sets a response in case of a Dynamic Page Cache hit.

Parameters

\Symfony\Component\HttpKernel\Event\RequestEvent $event: The event to process.

File

core/modules/dynamic_page_cache/src/EventSubscriber/DynamicPageCacheSubscriber.php, line 130

Class

DynamicPageCacheSubscriber
Returns cached responses as early and avoiding as much work as possible.

Namespace

Drupal\dynamic_page_cache\EventSubscriber

Code

public function onRequest(RequestEvent $event) {
    // Don't cache the response if the Dynamic Page Cache request policies are
    // not met. Store the result in a static keyed by current request, so that
    // onResponse() does not have to redo the request policy check.
    $request = $event->getRequest();
    $request_policy_result = $this->requestPolicy
        ->check($request);
    $this->requestPolicyResults[$request] = $request_policy_result;
    if ($request_policy_result === RequestPolicyInterface::DENY) {
        return;
    }
    // Sets the response for the current route, if cached.
    $cached = $this->cache
        ->get([
        'response',
    ], (new CacheableMetadata())->setCacheContexts($this->cacheContexts));
    if ($cached) {
        $response = $cached->data;
        $response->headers
            ->set(self::HEADER, 'HIT');
        $event->setResponse($response);
    }
}

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