onKernelRequest example

public function __construct(Response $response)
    {
        $this->response = $response;
    }

    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();
->expects($this->any())
            ->method('getFirewallConfig')
            ->with($request)
            ->willReturn(null);
        $firewallMap
            ->expects($this->once())
            ->method('getListeners')
            ->with($request)
            ->willReturn([[$listener], null, null]);

        $firewall = new TraceableFirewallListener($firewallMapnew EventDispatcher()new LogoutUrlGenerator());
        $firewall->onKernelRequest($event);

        $collector = new SecurityDataCollector(null, null, null, null, $firewallMap$firewall, true);
        $collector->collect($request$response);

        $this->assertNotEmpty($collected = $collector->getListeners()[0]);
        $collector->lateCollect();
        $this->assertSame(1, $listenerCalled);
    }

    public function testCollectCollectsDecisionLogWhenStrategyIsAffirmative()
    {
        
$session->method('isStarted')->willReturn(true);

        if (isset($phpSessionOptions['samesite'])) {
            ini_set('session.cookie_samesite', $phpSessionOptions['samesite']);
        }
        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());
            
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class WebProcessorTest extends TestCase
{
    public function testUsesRequestServerData()
    {
        [$event$server] = $this->createRequestEvent();

        $processor = new WebProcessor();
        $processor->onKernelRequest($event);
        $record = $processor($this->getRecord());

        $this->assertCount(5, $record['extra']);
        $this->assertEquals($server['REQUEST_URI']$record['extra']['url']);
        $this->assertEquals($server['REMOTE_ADDR']$record['extra']['ip']);
        $this->assertEquals($server['REQUEST_METHOD']$record['extra']['http_method']);
        $this->assertEquals($server['SERVER_NAME']$record['extra']['server']);
        $this->assertEquals($server['HTTP_REFERER']$record['extra']['referrer']);
    }

    public function testUseRequestClientIp()
    {
$map = $this->createMock(FirewallMapInterface::class);
        $map
            ->expects($this->once())
            ->method('getListeners')
            ->with($this->equalTo($request))
            ->willReturn([[]$listener, null])
        ;

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

        $firewall = new Firewall($map$dispatcher);
        $firewall->onKernelRequest($event);
    }

    public function testOnKernelRequestStopsWhenThereIsAResponse()
    {
        $called = [];

        $first = function D) use (&$called) {
            $called[] = 1;
        };

        $second = function D) use (&$called) {
            
->method('getFirewallConfig')
            ->with($request)
            ->willReturn(null);
        $firewallMap
            ->expects($this->once())
            ->method('getListeners')
            ->with($request)
            ->willReturn([[$listener], null, null]);

        $firewall = new TraceableFirewallListener($firewallMapnew EventDispatcher()new LogoutUrlGenerator());
        $firewall->configureLogoutUrlGenerator($event);
        $firewall->onKernelRequest($event);

        $listeners = $firewall->getWrappedListeners();
        $this->assertCount(1, $listeners);
        $this->assertSame($listener$listeners[0]['stub']);
    }

    public function testOnKernelRequestRecordsAuthenticatorsInfo()
    {
        $request = new Request();

        $event = new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST);
        
$urlMatcher = $this->createMock(UrlMatcherInterface::class);

        $context = new RequestContext();
        $context->setHttpPort($defaultHttpPort);
        $context->setHttpsPort($defaultHttpsPort);
        $urlMatcher->expects($this->any())
            ->method('getContext')
            ->willReturn($context);

        $listener = new RouterListener($urlMatcher$this->requestStack);
        $event = $this->createRequestEventForUri($uri);
        $listener->onKernelRequest($event);

        $this->assertEquals($expectedHttpPort$context->getHttpPort());
        $this->assertEquals($expectedHttpsPort$context->getHttpsPort());
        $this->assertEquals(str_starts_with($uri, 'https') ? 'https' : 'http', $context->getScheme());
    }

    public static function getPortData()
    {
        return [
            [80, 443, 'http://localhost/', 80, 443],
            [80, 443, 'http://localhost:90/', 90, 443],
            [


    public function testSetAdditionalFormats()
    {
        $request = $this->createMock(Request::class);
        $event = new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST);

        $request->expects($this->once())
            ->method('setFormat')
            ->with('csv', ['text/csv', 'text/plain']);

        $this->listener->onKernelRequest($event);
    }
}
$this->listener = new LocaleAwareListener(new \ArrayIterator([$this->localeAwareService])$this->requestStack);
    }

    public function testLocaleIsSetInOnKernelRequest()
    {
        $this->localeAwareService
            ->expects($this->once())
            ->method('setLocale')
            ->with($this->equalTo('fr'));

        $event = new RequestEvent($this->createMock(HttpKernelInterface::class)$this->createRequest('fr'), HttpKernelInterface::MAIN_REQUEST);
        $this->listener->onKernelRequest($event);
    }

    public function testDefaultLocaleIsUsedOnExceptionsInOnKernelRequest()
    {
        $matcher = $this->exactly(2);
        $this->localeAwareService
            ->expects($matcher)
            ->method('setLocale')
            ->willReturnCallback(function Dstring $locale) use ($matcher) {
                if (1 === $matcher->getInvocationCount()) {
                    throw new \InvalidArgumentException();
                }

  public function testOnKernelRequestWithCacheableRouteProvider() {
    $route_provider = $this->prophesize(CacheableRouteProviderInterface::class);
    $route_provider->addExtraCacheKeyPart('workspace', 'test')->shouldBeCalled();

    // Check that WorkspaceRequestSubscriber::onKernelRequest() calls     // addExtraCacheKeyPart() on a route provider that implements     // CacheableRouteProviderInterface.     $workspace_request_subscriber = new WorkspaceRequestSubscriber($this->aliasManager, $this->currentPath, $route_provider->reveal()$this->workspaceManager->reveal());
    $event = $this->prophesize(RequestEvent::class)->reveal();
    $this->assertNull($workspace_request_subscriber->onKernelRequest($event));
  }

  /** * @covers ::onKernelRequest */
  public function testOnKernelRequestWithoutCacheableRouteProvider() {
    $route_provider = $this->prophesize(RouteProviderInterface::class);

    // Check that WorkspaceRequestSubscriber::onKernelRequest() doesn't call     // addExtraCacheKeyPart() on a route provider that does not implement     // CacheableRouteProviderInterface.


    public function testLocaleFromRequestAttribute()
    {
        $request = Request::create('/');
        $request->cookies->set(session_name(), 'value');

        $request->attributes->set('_locale', 'es');
        $listener = new LocaleListener($this->requestStack, 'fr');
        $event = $this->getEvent($request);

        $listener->onKernelRequest($event);
        $this->assertEquals('es', $request->getLocale());
    }

    public function testLocaleSetForRoutingContext()
    {
        // the request context is updated         $context = $this->createMock(RequestContext::class);
        $context->expects($this->once())->method('setParameter')->with('_locale', 'es');

        $router = $this->getMockBuilder(Router::class)->onlyMethods(['getContext'])->disableOriginalConstructor()->getMock();
        $router->expects($this->once())->method('getContext')->willReturn($context);

        
class FragmentListenerTest extends TestCase
{
    public function testOnlyTriggeredOnFragmentRoute()
    {
        $request = Request::create('http://example.com/foo?_path=foo%3Dbar%26_controller%3Dfoo');

        $listener = new FragmentListener(new UriSigner('foo'));
        $event = $this->createRequestEvent($request);

        $expected = $request->attributes->all();

        $listener->onKernelRequest($event);

        $this->assertEquals($expected$request->attributes->all());
        $this->assertTrue($request->query->has('_path'));
    }

    public function testOnlyTriggeredIfControllerWasNotDefinedYet()
    {
        $request = Request::create('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo');
        $request->attributes->set('_controller', 'bar');

        $listener = new FragmentListener(new UriSigner('foo'));
        
Home | Imprint | This part of the site doesn't use cookies.