You are here

public function CacheableResponseSubscriber::onRespond in Akamai 8.3

Add cache tags header on cacheable responses.

Parameters

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

File

src/EventSubscriber/CacheableResponseSubscriber.php, line 70

Class

CacheableResponseSubscriber
Add cache tags headers on cacheable responses, for external caching systems.

Namespace

Drupal\akamai\EventSubscriber

Code

public function onRespond(FilterResponseEvent $event) {
  if (!$event
    ->isMasterRequest()) {
    return;
  }
  $response = $event
    ->getResponse();
  $config = $this->configFactory
    ->get('akamai.settings');
  $header = $config
    ->get('edge_cache_tag_header');

  // Send headers if response is cacheable and the setting is enabled.
  if ($header && $response instanceof CacheableResponseInterface) {
    $tags = $response
      ->getCacheableMetadata()
      ->getCacheTags();
    $blacklist = $config
      ->get('edge_cache_tag_header_blacklist');
    $blacklist = is_array($blacklist) ? $blacklist : [];
    $tags = array_filter($tags, function ($tag) use ($blacklist) {
      foreach ($blacklist as $prefix) {
        if (strpos($tag, $prefix) !== FALSE) {
          return FALSE;
        }
      }
      return TRUE;
    });

    // Instantiate our event.
    $event = new AkamaiHeaderEvents($tags);
    $this->eventDispatcher
      ->dispatch(AkamaiHeaderEvents::HEADER_CREATION, $event);
    $tags = $event->data;
    foreach ($tags as &$tag) {
      $tag = $this->tagFormatter
        ->format($tag);
    }
    $response->headers
      ->set('Edge-Cache-Tag', implode(',', $tags));
  }
}