src/App/Subscriber/HstsSubscriber.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. /**
  8.  * Injects HSTS headers for the core domain.
  9.  */
  10. final class HstsSubscriber implements EventSubscriberInterface
  11. {
  12.     public const HSTS_MAX_AGE 30 24 60 60;// 30 days
  13.     /**
  14.      * @var ParameterBagInterface
  15.      */
  16.     protected ParameterBagInterface $params;
  17.     /**
  18.      * @param ParameterBagInterface $params
  19.      */
  20.     public function __construct(ParameterBagInterface $params)
  21.     {
  22.         $this->params $params;
  23.     }
  24.     /**
  25.      *{@inheritDoc}
  26.      */
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             KernelEvents::RESPONSE => ['onKernelResponse'PHP_INT_MIN],
  31.         ];
  32.     }
  33.     /**
  34.      * @param ResponseEvent $event
  35.      * @return void
  36.      */
  37.     public function onKernelResponse(ResponseEvent $event): void
  38.     {
  39.         $host $event->getRequest()->getHost();
  40.         if ($event->getRequest()->isSecure() && ($host === $this->params->get('dashboard.hostname') || str_ends_with($host'.' $this->params->get('dashboard.hostname')))) {
  41.             $event->getResponse()->headers->set(
  42.                 'Strict-Transport-Security',
  43.                 sprintf(
  44.                     'max-age=%s',
  45.                     self::HSTS_MAX_AGE,
  46.                 ),
  47.             );
  48.         }
  49.     }
  50. }