vendor/nelmio/security-bundle/EventListener/ClickjackingListener.php line 43

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\HttpKernel\KernelEvents;
  15. /**
  16. * @final
  17. */
  18. class ClickjackingListener extends AbstractContentTypeRestrictableListener
  19. {
  20. private $paths;
  21. public function __construct(array $paths, array $contentTypes = array())
  22. {
  23. parent::__construct($contentTypes);
  24. $this->paths = $paths;
  25. }
  26. /**
  27. * @return array
  28. */
  29. public static function getSubscribedEvents()
  30. {
  31. return array(KernelEvents::RESPONSE => 'onKernelResponse');
  32. }
  33. /**
  34. * @param FilterResponseEvent|ResponseEvent $e
  35. */
  36. public function onKernelResponse($e)
  37. {
  38. // Compatibility with Symfony < 5 and Symfony >=5
  39. if (!$e instanceof FilterResponseEvent && !$e instanceof ResponseEvent) {
  40. 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)));
  41. }
  42. if (HttpKernelInterface::MASTER_REQUEST !== $e->getRequestType()) {
  43. return;
  44. }
  45. if (!$this->isContentTypeValid($e->getResponse())) {
  46. return;
  47. }
  48. $response = $e->getResponse();
  49. if ($response->isRedirection()) {
  50. return;
  51. }
  52. $currentPath = $e->getRequest()->getRequestUri() ?: '/';
  53. foreach ($this->paths as $path => $options) {
  54. if (preg_match('{'.$path.'}i', $currentPath)) {
  55. if ('ALLOW' === $options['header']) {
  56. $response->headers->remove('X-Frame-Options');
  57. } else {
  58. $response->headers->set('X-Frame-Options', $options['header']);
  59. }
  60. return;
  61. }
  62. }
  63. }
  64. }