RequestEvent example

->method('get')
            ->with('_security_key123')
            ->willReturn($token);
        $request = new Request([][][]['SESSIONNAME' => true]);
        $request->setSession($session);

        $tokenStorage->expects($this->once())
            ->method('setToken')
            ->with(null);

        $listener = new ContextListener($tokenStorage[], 'key123');
        $listener(new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST));
    }

    public static function provideInvalidToken()
    {
        return [
            ['foo'],
            ['O:8:"NotFound":0:{}'],
            [serialize(new \__PHP_Incomplete_Class())],
            [serialize(null)],
            [null],
        ];
    }
->method('decide')
            ->with($this->equalTo($token)$this->equalTo(['foo' => 'bar'])$this->equalTo($request))
            ->willReturn(false)
        ;

        $listener = new AccessListener(
            $tokenStorage,
            $accessDecisionManager,
            $accessMap
        );

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

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

        $accessMap = $this->createMock(AccessMapInterface::class);
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            
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();
$this->requestStack = new RequestStack();
        $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()) {
                    
// Clone the master credentials to a replica connection.     // Note this will result in two independent connection objects that happen     // to point to the same place.     $connection_info = Database::getConnectionInfo('default');
    Database::addConnectionInfo('default', 'replica', $connection_info['default']);

    /** @var \Drupal\Core\Database\ReplicaKillSwitch $service */
    $service = \Drupal::service('database.replica_kill_switch');
    $service->trigger();
    $class_loader = require $this->root . '/autoload.php';
    $kernel = new DrupalKernel('testing', $class_loader, FALSE);
    $event = new RequestEvent($kernel, Request::create('http://example.com'), HttpKernelInterface::MAIN_REQUEST);
    $service->checkReplicaServer($event);

    $db1 = Database::getConnection('default', 'default');
    $db2 = Database::getConnection('replica', 'default');

    $this->assertSame($db1$db2, 'System Init ignores secondaries when requested.');

    // Makes sure that session value set right.     $session = \Drupal::service('session');
    $this->assertTrue($session->has('ignore_replica_server'));
    $expected = \Drupal::time()->getRequestTime() + Settings::get('maximum_replication_lag', 300);
    
/** * @covers ::onRequest */
  public function testWithNonOptionRequest() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/example', 'GET');

    $route_provider = $this->prophesize(RouteProviderInterface::class);
    $route_provider->getRouteCollectionForRequest($request)->shouldNotBeCalled();

    $subscriber = new OptionsRequestSubscriber($route_provider->reveal());
    $event = new RequestEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST);
    $subscriber->onRequest($event);

    $this->assertFalse($event->hasResponse());
  }

  /** * @covers ::onRequest */
  public function testWithoutMatchingRoutes() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/example', 'OPTIONS');

    
public function testProcessorDoesNothingWhenNoRequest()
    {
        $processor = new RouteProcessor();

        $record = $processor(['extra' => []]);
        $this->assertEquals(['extra' => []]$record);
    }

    private function getRequestEvent(Request $request, int $requestType = HttpKernelInterface::MAIN_REQUEST): RequestEvent
    {
        return new RequestEvent($this->createMock(HttpKernelInterface::class)$request$requestType);
    }

    private function getFinishRequestEvent(Request $request): FinishRequestEvent
    {
        return new FinishRequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST);
    }

    private function mockEmptyRequest(): Request
    {
        return $this->mockRequest([]);
    }

    
private MockObject&AccessDecisionManagerInterface $accessDecisionManager;
    private Request $request;
    private RequestEvent $event;

    protected function setUp(): void
    {
        $this->tokenStorage = new TokenStorage();
        $this->userProvider = new InMemoryUserProvider(['kuba' => []]);
        $this->userChecker = $this->createMock(UserCheckerInterface::class);
        $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $this->request = new Request();
        $this->event = new RequestEvent($this->createMock(HttpKernelInterface::class)$this->request, HttpKernelInterface::MAIN_REQUEST);
    }

    public function testFirewallNameIsRequired()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('$firewallName must not be empty');
        new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
    }

    public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
    {
        
$dispatcher->addListener(LogoutEvent::classfunction D) use (&$logoutEventDispatched) {
            $logoutEventDispatched = true;
        });

        $request = new Request();

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request$options['logout_path'])
            ->willReturn(false);

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

        $this->assertFalse($logoutEventDispatched, 'LogoutEvent should not have been dispatched.');
    }

    public function testHandleMatchedPathWithCsrfValidation()
    {
        $tokenManager = $this->getTokenManager();
        $dispatcher = $this->getEventDispatcher();

        [$listener$tokenStorage$httpUtils$options] = $this->getListener($dispatcher$tokenManager);

        
$request = $this->createMock(Request::class);

        $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;
        };
$this->expectException(ConflictingHeadersException::class);
        $dispatcher = new EventDispatcher();
        $kernel = $this->createMock(HttpKernelInterface::class);

        $request = new Request();
        $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
        $request->server->set('REMOTE_ADDR', '1.1.1.1');
        $request->headers->set('FORWARDED', 'for=2.2.2.2');
        $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');

        $dispatcher->addListener(KernelEvents::REQUEST, [new ValidateRequestListener(), 'onKernelRequest']);
        $event = new RequestEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST);

        $dispatcher->dispatch($event, KernelEvents::REQUEST);
    }
}
/** * Handles a request to convert it to a response. * * Exceptions are not caught. * * @throws \LogicException If one of the listener does not behave as expected * @throws NotFoundHttpException When controller cannot be found */
    private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Response
    {
        // request         $event = new RequestEvent($this$request$type);
        $this->dispatcher->dispatch($event, KernelEvents::REQUEST);

        if ($event->hasResponse()) {
            return $this->filterResponse($event->getResponse()$request$type);
        }

        // load controller         if (false === $controller = $this->resolver->getController($request)) {
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
        }

        
/** * Handles a request to convert it to a response. * * Exceptions are not caught. * * @throws \LogicException If one of the listener does not behave as expected * @throws NotFoundHttpException When controller cannot be found */
    private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Response
    {
        // request         $event = new RequestEvent($this$request$type);
        $this->dispatcher->dispatch($event, KernelEvents::REQUEST);

        if ($event->hasResponse()) {
            return $this->filterResponse($event->getResponse()$request$type);
        }

        // load controller         if (false === $controller = $this->resolver->getController($request)) {
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
        }

        
->willReturn(false)
        ;

        $accessMap = $this->createMock(AccessMapInterface::class);
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->willReturn([[], 'http'])
        ;

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

        $listener = new ChannelListener($accessMap);
        $listener($event);

        $this->assertNull($event->getResponse());
    }

    public function testHandleWithSecuredRequestAndHttpsChannel()
    {
        $request = $this->createMock(Request::class);
        $request
            
$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());
            
Home | Imprint | This part of the site doesn't use cookies.