vendor/nelmio/security-bundle/EventListener/XssProtectionListener.php line 39

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Nelmio SecurityBundle.
  4.  *
  5.  * (c) Nelmio <hello@nelm.io>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Nelmio\SecurityBundle\EventListener;
  11. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  12. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  13. use Symfony\Component\HttpKernel\HttpKernelInterface;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. /**
  17.  * @final
  18.  */
  19. class XssProtectionListener implements EventSubscriberInterface
  20. {
  21.     private $enabled;
  22.     private $modeBlock;
  23.     private $reportUri;
  24.     public function __construct($enabled$modeBlock$reportUri null)
  25.     {
  26.         $this->enabled $enabled;
  27.         $this->modeBlock $modeBlock;
  28.         $this->reportUri $reportUri;
  29.     }
  30.     /**
  31.      * @param FilterResponseEvent|ResponseEvent $e
  32.      */
  33.     public function onKernelResponse($e)
  34.     {
  35.         // Compatibility with Symfony < 5 and Symfony >=5
  36.         if (!$e instanceof FilterResponseEvent && !$e instanceof ResponseEvent) {
  37.             throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given'\class_exists(ResponseEvent::class) ? ResponseEvent::class : FilterResponseEvent::class, \is_object($e) ? \get_class($e) : \gettype($e)));
  38.         }
  39.         if (HttpKernelInterface::MASTER_REQUEST !== $e->getRequestType()) {
  40.             return;
  41.         }
  42.         $response $e->getResponse();
  43.         if ($response->isRedirection()) {
  44.             return;
  45.         }
  46.         $value '0';
  47.         if ($this->enabled) {
  48.             $value '1';
  49.             if ($this->modeBlock) {
  50.                 $value .= '; mode=block';
  51.             }
  52.             if ($this->reportUri) {
  53.                 $value .= '; report=' $this->reportUri;
  54.             }
  55.         }
  56.         $response->headers->set('X-XSS-Protection'$value);
  57.     }
  58.     /**
  59.      * @return array
  60.      */
  61.     public static function getSubscribedEvents()
  62.     {
  63.         return array(KernelEvents::RESPONSE => 'onKernelResponse');
  64.     }
  65.     public static function fromConfig(array $config)
  66.     {
  67.         $enabled $config['enabled'];
  68.         $modeBlock $config['mode_block'];
  69.         $reportUri $config['report_uri'];
  70.         return new self($enabled$modeBlock$reportUri);
  71.     }
  72. }