ResponseEvent example

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');

        
class DisallowRobotsIndexingListenerTest extends TestCase
{
    /** * @dataProvider provideResponses */
    public function testInvoke(?string $expected, array $responseArgs)
    {
        $response = new Response(...$responseArgs);
        $listener = new DisallowRobotsIndexingListener();

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

        $listener->onResponse($event);

        $this->assertSame($expected$response->headers->get('X-Robots-Tag'), 'Header doesn\'t match expectations');
    }

    public static function provideResponses(): iterable
    {
        yield 'No header' => ['noindex', []];

        yield 'Header already set' => [
            

  protected function filterResponse(Request $request$request_type, Response $response) {
    assert($request_type === HttpKernelInterface::MAIN_REQUEST || $request_type === HttpKernelInterface::SUB_REQUEST);
    $this->requestStack->push($request);
    $event = new ResponseEvent($this->httpKernel, $request$request_type$response);
    $this->eventDispatcher->dispatch($event, KernelEvents::RESPONSE);
    $filtered_response = $event->getResponse();
    $this->requestStack->pop();
    return $filtered_response;
  }

  /** * Sends </body> and everything after it. * * @param string $post_body * The HTML response's content after the closing </body> tag. */
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();

  public function testPrepareResponseForIeFormRequestsWithFileUpload() {
    $request = Request::create('/example', 'POST');
    $request->headers->set('Accept', 'text/html');
    $response = new AjaxResponse([]);
    $response->headers->set('Content-Type', 'application/json; charset=utf-8');

    $ajax_response_attachments_processor = $this->createMock('\Drupal\Core\Render\AttachmentsResponseProcessorInterface');
    $subscriber = new AjaxResponseSubscriber($ajax_response_attachments_processor);
    $event = new ResponseEvent(
      $this->createMock('\Symfony\Component\HttpKernel\HttpKernelInterface'),
      $request,
      HttpKernelInterface::MAIN_REQUEST,
      $response
    );
    $subscriber->onResponse($event);
    $this->assertEquals('text/html; charset=utf-8', $response->headers->get('Content-Type'));
    $this->assertEquals('<textarea>[]</textarea>', $response->getContent());
  }

}


  /** * @dataProvider providerTestOnResponse * * @param string $content * The content for the request. * @param string $expected_content * The expected content from the response. */
  public function testOnResponse($content$expected_content) {
    $event = new ResponseEvent(
      $this->prophesize(HttpKernelInterface::class)->reveal(),
      Request::create('/'),
      HttpKernelInterface::MAIN_REQUEST,
      new Response($content, 200, [
        'Content-Type' => 'application/rss+xml',
      ])
    );

    $url_filter = new RssResponseRelativeUrlFilter();
    $url_filter->onResponse($event);

    
$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);

        $this->assertEquals('', $event->getResponse()->headers->get('content-type'));
    }

    public function testFilterSetsNonDefaultCharsetIfNotOverridden()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...), 1);

        $response = new Response('foo');

        
/** * @covers ::onResponse * @dataProvider providerTestSerialization */
  public function testSerialization($data$expected_response = FALSE) {
    $request = new Request();
    $route_match = new RouteMatch('test', new Route('/rest/test', ['_rest_resource_config' => 'restplugin']['_format' => 'json']));

    $handler_response = new ResourceResponse($data);
    $resource_response_subscriber = $this->getFunctioningResourceResponseSubscriber($route_match);
    $event = new ResponseEvent(
      $this->prophesize(HttpKernelInterface::class)->reveal(),
      $request,
      HttpKernelInterface::MAIN_REQUEST,
      $handler_response
    );
    $resource_response_subscriber->onResponse($event);

    // Content is a serialized version of the data we provided.     $this->assertEquals($expected_response !== FALSE ? $expected_response : Json::encode($data)$event->getResponse()->getContent());
  }

  

        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());
            

  public function testAttachedSettings() {
    $assert = function D$message) {
      $response = new AjaxResponse();
      $response->setAttachments([
        'library' => ['core/drupalSettings'],
        'drupalSettings' => ['foo' => 'bar'],
      ]);

      $ajax_response_attachments_processor = \Drupal::service('ajax_response.attachments_processor');
      $subscriber = new AjaxResponseSubscriber($ajax_response_attachments_processor);
      $event = new ResponseEvent(
        \Drupal::service('http_kernel'),
        new Request(),
        HttpKernelInterface::MAIN_REQUEST,
        $response
      );
      $subscriber->onResponse($event);
      $expected = [
        'command' => 'settings',
      ];
      $this->assertCommand($response->getCommands()$expected$message);
    };

    
$this->assertNull($error);
    }

    private function dispatchResponseEvent(FirePHPHandler $handler, Request $request): Response
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::RESPONSE, $handler->onKernelResponse(...));

        return $dispatcher
            ->dispatch(
                new ResponseEvent(
                    $this->createStub(HttpKernelInterface::class),
                    $request,
                    HttpKernelInterface::MAIN_REQUEST,
                    new Response()
                ),
                KernelEvents::RESPONSE
            )
            ->getResponse();
    }
}

        ];
    }

    /** * @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');
        
$path_matcher->reveal(),
      $language_manager
    );

    // A link that might otherwise be set 'active'.     $content = '<a data-drupal-link-system-path="other-page">Other page</a>';

    // Assert response with non-html content type gets ignored.     $response = new Response();
    $response->setContent($content);
    $response->headers->get('Content-Type', 'application/json');
    $subscriber->onResponse(new ResponseEvent(
      $this->prophesize(KernelInterface::class)->reveal(),
      $request_stack->getCurrentRequest(),
      HttpKernelInterface::MAIN_REQUEST,
      $response
    ));
    $this->assertSame($response->getContent()$content);
  }

  /** * Tests certain response types ignored by the ActiveLinkResponseFilter. * * @covers ::onResponse */
private function getResponse()
    {
        $response = new Response();
        $response->headers = $this->createMock(ResponseHeaderBag::class);

        return $response;
    }

    private function getEvent(Request $request, Response $response, int $type = HttpKernelInterface::MAIN_REQUEST): ResponseEvent
    {
        return new ResponseEvent($this->createMock(HttpKernelInterface::class)$request$type$response);
    }
}

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']);
    }
Home | Imprint | This part of the site doesn't use cookies.