<?php
namespace App\Subscriber;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Injects HSTS headers for the core domain.
*/
final class HstsSubscriber implements EventSubscriberInterface
{
public const HSTS_MAX_AGE = 30 * 24 * 60 * 60;// 30 days
/**
* @var ParameterBagInterface
*/
protected ParameterBagInterface $params;
/**
* @param ParameterBagInterface $params
*/
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
/**
*{@inheritDoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', PHP_INT_MIN],
];
}
/**
* @param ResponseEvent $event
* @return void
*/
public function onKernelResponse(ResponseEvent $event): void
{
$host = $event->getRequest()->getHost();
if ($event->getRequest()->isSecure() && ($host === $this->params->get('dashboard.hostname') || str_ends_with($host, '.' . $this->params->get('dashboard.hostname')))) {
$event->getResponse()->headers->set(
'Strict-Transport-Security',
sprintf(
'max-age=%s',
self::HSTS_MAX_AGE,
),
);
}
}
}