You are here

class HstsSubscriber in HTTP Strict Transport Security 8

Subscribes to the kernel request event to add HAL media types.

Hierarchy

  • class \Drupal\hsts\HstsSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of HstsSubscriber

1 string reference to 'HstsSubscriber'
hsts.services.yml in ./hsts.services.yml
hsts.services.yml
1 service uses HstsSubscriber
hsts.subscriber in ./hsts.services.yml
Drupal\hsts\HstsSubscriber

File

src/HstsSubscriber.php, line 18
Contains \Drupal\hsts\HstsSubscriber.

Namespace

Drupal\hsts
View source
class HstsSubscriber implements EventSubscriberInterface {

  /**
   * A config object for the HSTS configuration.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * Constructs a FinishResponseSubscriber object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   A config factory for retrieving required config objects.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->config = $config_factory
      ->get('hsts.settings');
  }

  /**
   * Sets the header in all responses to include the HSTS max-age value.
   *
   * @param Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   The event to process.
   */
  public function onRespond(FilterResponseEvent $event) {
    if (!$this->config
      ->get('enabled')) {
      return;
    }

    // Add the max age header.
    $header = 'max-age=' . (int) $this->config
      ->get('max_age');
    if ($this->config
      ->get('subdomains')) {

      // Include subdomains
      $header .= '; includeSubDomains';
    }
    if ($this->config
      ->get('preload')) {

      // Add preload directive.
      $header .= '; preload';
    }

    // Add the header.
    $event
      ->getResponse()->headers
      ->set('Strict-Transport-Security', $header);
  }

  /**
   * Registers the methods in this class that should be listeners.
   *
   * @return array
   *   An array of event listener definitions.
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = [
      'onRespond',
    ];
    return $events;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
HstsSubscriber::$config protected property A config object for the HSTS configuration.
HstsSubscriber::getSubscribedEvents public static function Registers the methods in this class that should be listeners.
HstsSubscriber::onRespond public function Sets the header in all responses to include the HSTS max-age value.
HstsSubscriber::__construct public function Constructs a FinishResponseSubscriber object.