Nelmio\SecurityBundle\EventListener\ExternalRedirectListener::onKernelResponse PHP Method

onKernelResponse() public method

public onKernelResponse ( FilterResponseEvent $e )
$e Symfony\Component\HttpKernel\Event\FilterResponseEvent
    public function onKernelResponse(FilterResponseEvent $e)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $e->getRequestType()) {
            return;
        }
        $response = $e->getResponse();
        if (!$response->isRedirect()) {
            return;
        }
        $target = $response->headers->get('Location');
        if (!$this->isExternalRedirect($e->getRequest()->getUri(), $target)) {
            return;
        }
        if (null !== $this->targetValidator && $this->targetValidator->isTargetAllowed($target)) {
            return;
        }
        if ($this->logger) {
            $this->logger->warn('External redirect detected from ' . $e->getRequest()->getUri() . ' to ' . $response->headers->get('Location'));
        }
        if ($this->abort) {
            throw new HttpException(403, 'Invalid Redirect Given: ' . $response->headers->get('Location'));
        }
        if ($this->override) {
            $parameters = array();
            if ($this->forwardAs) {
                $parameters[$this->forwardAs] = $response->headers->get('Location');
            }
            if (false === strpos($this->override, '/')) {
                if (!$this->generator) {
                    throw new \UnexpectedValueException('The listener needs a router/UrlGeneratorInterface object to override invalid redirects with routes');
                }
                $response->headers->set('Location', $this->generator->generate($this->override, $parameters));
            } else {
                $query = '';
                if (count($parameters) > 0) {
                    $query = strpos($this->override, '?') === false ? '?' : '&';
                    $query .= http_build_query($parameters, null, '&');
                }
                $response->headers->set('Location', $this->override . $query);
            }
        }
    }

Usage Example

 public function testListenerSkipsSubReqs()
 {
     $listener = new ExternalRedirectListener(true);
     $request = Request::create('http://test.org/');
     $response = new RedirectResponse('http://foo.com/');
     $event = new FilterResponseEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $response);
     $listener->onKernelResponse($event);
     $this->assertSame(true, $response->isRedirect());
     $this->assertSame('http://foo.com/', $response->headers->get('Location'));
 }