You are here

class CacheControlOverrideSubscriber in Cache Control Override 8

Cache Control Override.

Hierarchy

  • class \Drupal\cache_control_override\EventSubscriber\CacheControlOverrideSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of CacheControlOverrideSubscriber

1 string reference to 'CacheControlOverrideSubscriber'
cache_control_override.services.yml in ./cache_control_override.services.yml
cache_control_override.services.yml
1 service uses CacheControlOverrideSubscriber
cache_control_override.cache_control_override_subscriber in ./cache_control_override.services.yml
Drupal\cache_control_override\EventSubscriber\CacheControlOverrideSubscriber

File

src/EventSubscriber/CacheControlOverrideSubscriber.php, line 14

Namespace

Drupal\cache_control_override\EventSubscriber
View source
class CacheControlOverrideSubscriber implements EventSubscriberInterface {

  /**
   * Overrides cache control header if any of override methods are enabled.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   The event to process.
   */
  public function onRespond(FilterResponseEvent $event) {
    if (!$event
      ->isMasterRequest()) {
      return;
    }
    $response = $event
      ->getResponse();

    // If the current response isn't an implementation of the
    // CacheableResponseInterface, then there is nothing we can override.
    if (!$response instanceof CacheableResponseInterface) {
      return;
    }

    // If FinishResponseSubscriber didn't set the response as cacheable, then
    // don't override anything.
    if (!$response->headers
      ->hasCacheControlDirective('max-age') || !$response->headers
      ->hasCacheControlDirective('public')) {
      return;
    }
    $max_age = $response
      ->getCacheableMetadata()
      ->getCacheMaxAge();

    // We treat permanent cache max-age as default therefore we don't override
    // the max-age.
    if ($max_age != Cache::PERMANENT) {
      $response->headers
        ->set('Cache-Control', 'public, max-age=' . $max_age);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = [
      'onRespond',
    ];
    return $events;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheControlOverrideSubscriber::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to.
CacheControlOverrideSubscriber::onRespond public function Overrides cache control header if any of override methods are enabled.