onKernelResponse example


        $cookie = new Cookie('rememberme', null, 0, '/', null, false, true, false, null);

        $request = $this->getRequest([
            ResponseListener::COOKIE_ATTR_NAME => $cookie,
        ]);

        $response = $this->getResponse();
        $response->headers->expects($this->once())->method('setCookie')->with($cookie);

        $listener = new ResponseListener();
        $listener->onKernelResponse($this->getEvent($request$response));
    }

    public function testRememberMeCookieIsNotSendWithResponseForSubRequests()
    {
        $cookie = new Cookie('rememberme', null, 0, '/', null, false, true, false, null);

        $request = $this->getRequest([
            ResponseListener::COOKIE_ATTR_NAME => $cookie,
        ]);

        $response = $this->getResponse();
        
$mainRequest = $this->createMock(Request::class);
        $subRequest = $this->createMock(Request::class);
        $response = $this->createMock(Response::class);

        $requestStack = new RequestStack();
        $requestStack->push($mainRequest);

        $onlyException = true;
        $listener = new ProfilerListener($profiler$requestStack, null, $onlyException);

        // main request         $listener->onKernelResponse(new ResponseEvent($kernel$mainRequest, Kernel::MAIN_REQUEST, $response));

        // sub request         $listener->onKernelException(new ExceptionEvent($kernel$subRequest, Kernel::SUB_REQUEST, new HttpException(404)));
        $listener->onKernelResponse(new ResponseEvent($kernel$subRequest, Kernel::SUB_REQUEST, $response));

        $listener->onKernelTerminate(new TerminateEvent($kernel$mainRequest$response));
    }

    /** * @dataProvider collectRequestProvider */
    
use Symfony\Component\HttpKernel\KernelEvents;

class SurrogateListenerTest extends TestCase
{
    public function testFilterDoesNothingForSubRequests()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->createMock(HttpKernelInterface::class);
        $response = new Response('foo <esi:include src="" />');
        $listener = new SurrogateListener(new Esi());

        $dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...));
        $event = new ResponseEvent($kernelnew Request(), HttpKernelInterface::SUB_REQUEST, $response);
        $dispatcher->dispatch($event, KernelEvents::RESPONSE);

        $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
    }

    public function testFilterWhenThereIsSomeEsiIncludes()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->createMock(HttpKernelInterface::class);
        $response = new Response('foo <esi:include src="" />');
        
class AddLinkHeaderListenerTest extends TestCase
{
    public function testOnKernelResponse()
    {
        $request = new Request([][]['_links' => new GenericLinkProvider([new Link('preload', '/foo')])]);
        $response = new Response('', 200, ['Link' => '<https://demo.api-platform.com/docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"']);

        $subscriber = new AddLinkHeaderListener();

        $event = new ResponseEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST, $response);

        $subscriber->onKernelResponse($event);

        $this->assertInstanceOf(EventSubscriberInterface::class$subscriber);

        $expected = [
            '<https://demo.api-platform.com/docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"',
            '</foo>; rel="preload"',
        ];

        $this->assertEquals($expected$response->headers->all()['link']);
    }

    
use Symfony\Component\HttpKernel\KernelEvents;

class ResponseListenerTest extends TestCase
{
    private EventDispatcher $dispatcher;
    private MockObject&HttpKernelInterface $kernel;

    protected function setUp(): void
    {
        $this->dispatcher = new EventDispatcher();
        $listener = new ResponseListener('UTF-8');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...));

        $this->kernel = $this->createMock(HttpKernelInterface::class);
    }

    public function testFilterDoesNothingForSubRequests()
    {
        $response = new Response('foo');

        $event = new ResponseEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
        $this->dispatcher->dispatch($event, KernelEvents::RESPONSE);

        
/** * @dataProvider provideRedirects */
    public function testHtmlRedirectionIsIntercepted($statusCode)
    {
        $response = new Response('Some content', $statusCode);
        $response->headers->set('X-Debug-Token', 'xxxxxxxx');
        $event = new ResponseEvent($this->createMock(Kernel::class)new Request(), HttpKernelInterface::MAIN_REQUEST, $response);

        $listener = new WebDebugToolbarListener($this->getTwigMock('Redirection'), true);
        $listener->onKernelResponse($event);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('Redirection', $response->getContent());
    }

    public function testNonHtmlRedirectionIsNotIntercepted()
    {
        $response = new Response('Some content', '301');
        $response->headers->set('X-Debug-Token', 'xxxxxxxx');
        $event = new ResponseEvent($this->createMock(Kernel::class)new Request([][]['_format' => 'json']), HttpKernelInterface::MAIN_REQUEST, $response);

        

        session_set_cookie_params(0, $phpSessionOptions['path'] ?? null, $phpSessionOptions['domain'] ?? null, $phpSessionOptions['secure'] ?? null, $phpSessionOptions['httponly'] ?? null);

        $listener = new SessionListener(new Container(), false, $sessionOptions);
        $kernel = $this->createMock(HttpKernelInterface::class);

        $request = new Request();
        $listener->onKernelRequest(new RequestEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST));

        $request->setSession($session);
        $response = new Response();
        $listener->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $response));

        $cookies = $response->headers->getCookies();

        if ($sessionOptions['use_cookies'] ?? true) {
            $this->assertCount(1, $cookies);
            $this->assertSame('PHPSESSID', $cookies[0]->getName());
            $this->assertSame('123456', $cookies[0]->getValue());
            $this->assertSame($expectedSessionOptions['cookie_path']$cookies[0]->getPath());
            $this->assertSame($expectedSessionOptions['cookie_domain']$cookies[0]->getDomain());
            $this->assertSame($expectedSessionOptions['cookie_secure']$cookies[0]->isSecure());
            $this->assertSame($expectedSessionOptions['cookie_httponly']$cookies[0]->isHttpOnly());
            
$session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $event = new ResponseEvent(
            $this->createMock(HttpKernelInterface::class),
            $request,
            HttpKernelInterface::MAIN_REQUEST,
            new Response()
        );

        $listener = new ContextListener($tokenStorage[], 'session', null, new EventDispatcher());
        $listener->onKernelResponse($event);

        $this->assertTrue($session->isStarted());
    }

    public function testOnKernelResponseWithoutSessionNorToken()
    {
        $request = new Request();
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $event = new ResponseEvent(
            
public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response
    {
        return $this->response;
    }
};

$listener->onKernelRequest(new RequestEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST));
$session = $request->getSession();
$session->set('foo', 'bar');
$session->invalidate();

$listener->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $r));

$r->sendHeaders();
$this->cache = new Cache();
        $this->request = $this->createRequest($this->cache);
        $this->event = $this->createEventMock($this->request, $this->response);
    }

    public function testWontReassignResponseWhenResponseIsUnsuccessful()
    {
        $response = $this->event->getResponse();

        $this->response->setStatusCode(500);

        $this->listener->onKernelResponse($this->event);

        $this->assertSame($response$this->event->getResponse());
    }

    public function testWontReassignResponseWhenNoConfigurationIsPresent()
    {
        $response = $this->event->getResponse();

        $this->request->attributes->remove('_cache');

        $this->listener->onKernelResponse($this->event);

        
static fn (string $key): bool => str_starts_with($key, 'x-wf-1-1-1'),
                \ARRAY_FILTER_USE_KEY
            )
        );
    }

    public function testEmptyLog()
    {
        $handler = $this->createHandler();

        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::RESPONSE, $handler->onKernelResponse(...));

        $request = new Request();
        $request->headers->set('User-Agent', 'Mozilla/5.0 (FirePHP/1.0)');

        $response = $this->dispatchResponseEvent($handler$request);

        self::assertSame(
            [],
            array_filter(
                $response->headers->all(),
                static fn (string $key): bool => str_starts_with($key, 'x-wf-1-1-1'),
                
public function supports(Request $request): ?bool
    {
        return null; // always run authenticate() lazily with lazy firewalls     }

    /** * Reads the Security Token from the session. */
    public function authenticate(RequestEvent $event): void
    {
        if (!$this->registered && null !== $this->dispatcher && $event->isMainRequest()) {
            $this->dispatcher->addListener(KernelEvents::RESPONSE, $this->onKernelResponse(...));
            $this->registered = true;
        }

        $request = $event->getRequest();
        $session = $request->hasPreviousSession() ? $request->getSession() : null;

        $request->attributes->set('_security_firewall_run', $this->sessionKey);

        if (null !== $session) {
            $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : 0;
            $usageIndexReference = \PHP_INT_MIN;
            
public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie()
    {
        $request = $this->createRequest();
        $request->cookies->add([
            'sf_redirect' => '{}',
        ]);

        $kernel = $this->createMock(HttpKernelInterface::class);

        $c = new RequestDataCollector();
        $c->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $this->createResponse()));

        $this->assertTrue($request->attributes->get('_redirected'));
    }

    public function testItSetsARedirectCookieIfTheResponseIsARedirection()
    {
        $c = new RequestDataCollector();

        $response = $this->createResponse();
        $response->setStatusCode(302);
        $response->headers->set('Location', '/somewhere-else');

        
Home | Imprint | This part of the site doesn't use cookies.