You are here

public function ApeSubscriber::onRespond in Advanced Page Expiration 8

Sets extra headers on successful responses.

Parameters

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

File

src/EventSubscriber/ApeSubscriber.php, line 72

Class

ApeSubscriber
Alter Cache-control header based on configuration of ape.

Namespace

Drupal\ape\EventSubscriber

Code

public function onRespond(FilterResponseEvent $event) {
  if (!$event
    ->isMasterRequest()) {
    return;
  }
  $response = $event
    ->getResponse();

  // APE Cache only works with cacheable responses. It does not work
  // with plain Response objects such as JsonResponse and etc.
  if (!$response instanceof CacheableResponseInterface) {
    return;
  }
  $maxAge = ape_cache_set();

  // Check to see if another module or hook has already set an age. This
  // allows rules or other module integration to take precedent.
  if (is_null($maxAge)) {

    // Check if request matches the alternatives, otherwise use default.

    /* @var \Drupal\system\Plugin\Condition\RequestPath $condition */
    $condition = $this->conditionManager
      ->createInstance('request_path');
    $condition
      ->setConfig('pages', $this->configApe
      ->get('alternatives'));
    if (!empty($this->configApe
      ->get('alternatives')) && $condition
      ->evaluate()) {
      $maxAge = $this->configApe
        ->get('lifetime.alternatives');
    }
    else {
      $maxAge = $this->configSystem
        ->get('cache.page.max_age');
    }
  }
  switch ($response
    ->getStatusCode()) {
    case 301:
      $maxAge = $this->configApe
        ->get('lifetime.301');
      break;
    case 302:
      $maxAge = $this->configApe
        ->get('lifetime.302');
      break;
    case 403:
      $maxAge = 0;
      break;
    case 404:
      $maxAge = $this->configApe
        ->get('lifetime.404');
      break;
  }

  // Allow max age to be altered by hook_ape_cache_alter().
  $originalMaxAge = $maxAge;
  \Drupal::moduleHandler()
    ->alter('ape_cache', $maxAge, $originalMaxAge);

  // Finally set cache header.
  $this
    ->setCacheHeader($event, $maxAge);
}