vendor/nelmio/security-bundle/src/EventListener/XssProtectionListener.php line 35

  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Nelmio SecurityBundle.
  5.  *
  6.  * (c) Nelmio <hello@nelm.io>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Nelmio\SecurityBundle\EventListener;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. final class XssProtectionListener implements EventSubscriberInterface
  16. {
  17.     use KernelEventForwardCompatibilityTrait;
  18.     private bool $enabled;
  19.     private bool $modeBlock;
  20.     private ?string $reportUri;
  21.     public function __construct(bool $enabledbool $modeBlock, ?string $reportUri null)
  22.     {
  23.         $this->enabled $enabled;
  24.         $this->modeBlock $modeBlock;
  25.         $this->reportUri $reportUri;
  26.     }
  27.     public function onKernelResponse(ResponseEvent $e): void
  28.     {
  29.         if (!$this->isMainRequest($e)) {
  30.             return;
  31.         }
  32.         $response $e->getResponse();
  33.         if ($response->isRedirection()) {
  34.             return;
  35.         }
  36.         $value '0';
  37.         if ($this->enabled) {
  38.             $value '1';
  39.             if ($this->modeBlock) {
  40.                 $value .= '; mode=block';
  41.             }
  42.             if (null !== $this->reportUri) {
  43.                 $value .= '; report='.$this->reportUri;
  44.             }
  45.         }
  46.         $response->headers->set('X-XSS-Protection'$value);
  47.     }
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [KernelEvents::RESPONSE => 'onKernelResponse'];
  51.     }
  52.     /**
  53.      * @phpstan-param array{enabled: bool, mode_block: bool, report_uri: string|null} $config
  54.      */
  55.     public static function fromConfig(array $config): self
  56.     {
  57.         $enabled $config['enabled'];
  58.         $modeBlock $config['mode_block'];
  59.         $reportUri $config['report_uri'];
  60.         return new self($enabled$modeBlock$reportUri);
  61.     }
  62. }