You are here

public function CloudFlareCacheTagHeaderGenerator::onResponse in CloudFlare 8

Generates a 'Cache-Tag' header in the format expected by CloudFlare.

Parameters

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

File

modules/cloudflarepurger/src/EventSubscriber/CloudFlareCacheTagHeaderGenerator.php, line 39

Class

CloudFlareCacheTagHeaderGenerator
Generates a 'Cache-Tag' header in the format expected by CloudFlare.

Namespace

Drupal\cloudflarepurger\EventSubscriber

Code

public function onResponse(FilterResponseEvent $event) {
  if (!$event
    ->isMasterRequest()) {
    return;
  }

  // If there are no X-Drupal-Cache-Tags headers, then there is also no work
  // to be done.
  $response = $event
    ->getResponse();
  if (!$response instanceof CacheableResponseInterface) {
    return;
  }
  $cache_metadata = $response
    ->getCacheableMetadata();
  $cache_tags = $cache_metadata
    ->getCacheTags();
  $has_tags = !empty($cache_tags);
  if (!$has_tags) {
    return;
  }
  $response = $event
    ->getResponse();
  $cloudflare_cachetag_header_value = static::drupalCacheTagsToCloudFlareCacheTag($cache_tags);

  // Hash each cache tag to make the header fit, at the cost of potentially
  // invalidating too much (cfr. hash collisions).
  $cache_tags = explode(',', $cloudflare_cachetag_header_value);
  $hashes = static::cacheTagsToHashes($cache_tags);
  $cloudflare_cachetag_header_value = implode(',', $hashes);
  $response->headers
    ->set('Cache-Tag', $cloudflare_cachetag_header_value);
}