<?php
/*
* This file is part of the Nelmio SecurityBundle.
*
* (c) Nelmio <hello@nelm.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nelmio\SecurityBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* @final
*/
class ContentTypeListener
{
protected $nosniff;
public function __construct($nosniff)
{
$this->nosniff = $nosniff;
}
/**
* @param FilterResponseEvent|ResponseEvent $e
*/
public function onKernelResponse($e)
{
// Compatibility with Symfony < 5 and Symfony >=5
if (!$e instanceof FilterResponseEvent && !$e instanceof ResponseEvent) {
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)));
}
if (HttpKernelInterface::MASTER_REQUEST !== $e->getRequestType()) {
return;
}
if (!$this->nosniff) {
return;
}
$response = $e->getResponse();
if ($response->isRedirection()) {
return;
}
$response->headers->add(array('X-Content-Type-Options' => 'nosniff'));
}
}