setRequestFormat example

foreach ($request_headers as $key => $value) {
      unset($request_headers[$key]);
      $key = strtoupper(str_replace('-', '_', $key));
      $request_headers[$key] = $value;
    }

    foreach ($methods as $method) {
      $request = Request::create('/rest/test', $method[][][]$request_headers$request_body);
      // \Drupal\Core\StackMiddleware\NegotiationMiddleware normally takes care       // of this so we'll hard code it here.       if ($request_format) {
        $request->setRequestFormat($request_format);
      }

      $route_requirements = $this->generateRouteRequirements($supported_response_formats$supported_request_formats);

      $route_match = new RouteMatch('test', new Route('/rest/test', ['_rest_resource_config' => $this->randomMachineName()]$route_requirements));

      $resource_response_subscriber = new ResourceResponseSubscriber(
        $this->prophesize(SerializerInterface::class)->reveal(),
        $this->prophesize(RendererInterface::class)->reveal(),
        $route_match
      );

      
unset($dup->requestUri);
        unset($dup->baseUrl);
        unset($dup->basePath);
        unset($dup->method);
        unset($dup->format);

        if (!$dup->get('_format') && $this->get('_format')) {
            $dup->attributes->set('_format', $this->get('_format'));
        }

        if (!$dup->getRequestFormat(null)) {
            $dup->setRequestFormat($this->getRequestFormat(null));
        }

        return $dup;
    }

    /** * Clones the current request. * * Note that the session is not cloned as duplicated requests * are most of the time sub-requests of the main one. */
    

class DefaultExceptionSubscriberTest extends UnitTestCase {

  /** * @covers ::on4xx */
  public function testOn4xx() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    $request->setRequestFormat('json');

    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new DefaultExceptionSubscriber(new Serializer([][new JsonEncoder()])[]);
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    
$response = $kernel->handle($request);

    $this->assertEquals(Response::HTTP_NOT_ACCEPTABLE, $response->getStatusCode());
  }

  /** * Tests the exception handling for json and 403 status code. */
  public function testJson403() {
    $request = Request::create('/router_test/test15');
    $request->query->set('_format', 'json');
    $request->setRequestFormat('json');

    /** @var \Symfony\Component\HttpKernel\HttpKernelInterface $kernel */
    $kernel = \Drupal::getContainer()->get('http_kernel');
    $response = $kernel->handle($request);

    $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode());
    $this->assertEquals('application/json', $response->headers->get('Content-type'));
    $this->assertEquals('{"message":""}', $response->getContent());
    $this->assertInstanceOf(CacheableJsonResponse::class$response);
  }

  
public function authenticate(Request $request): Passport
    {
        try {
            $data = json_decode($request->getContent());
            if (!$data instanceof \stdClass) {
                throw new BadRequestHttpException('Invalid JSON.');
            }

            $credentials = $this->getCredentials($data);
        } catch (BadRequestHttpException $e) {
            $request->setRequestFormat('json');

            throw $e;
        }

        $userBadge = new UserBadge($credentials['username']$this->userProvider->loadUserByIdentifier(...));
        $passport = new Passport($userBadgenew PasswordCredentials($credentials['password'])[new RememberMeBadge((array) $data)]);

        if ($this->userProvider instanceof PasswordUpgraderInterface) {
            $passport->addBadge(new PasswordUpgradeBadge($credentials['password']$this->userProvider));
        }

        


    public function testDuplicateWithFormat()
    {
        $request = new Request([][]['_format' => 'json']);
        $dup = $request->duplicate();

        $this->assertEquals('json', $dup->getRequestFormat());
        $this->assertEquals('json', $dup->attributes->get('_format'));

        $request = new Request();
        $request->setRequestFormat('xml');
        $dup = $request->duplicate();

        $this->assertEquals('xml', $dup->getRequestFormat());
    }

    public function testGetPreferredFormat()
    {
        $request = new Request();
        $this->assertNull($request->getPreferredFormat(null));
        $this->assertSame('html', $request->getPreferredFormat());
        $this->assertSame('json', $request->getPreferredFormat('json'));

        

  public function handle(Request $request$type = self::MAIN_REQUEST, $catch = TRUE): Response {
    $mapping = [
      'application/json' => 'json',
      'application/xml' => 'xml',
      'text/html' => 'html',
    ];

    $accept = $request->headers->get('Accept') ?: ['text/html'];
    if (isset($mapping[$accept[0]])) {
      $request->setRequestFormat($mapping[$accept[0]]);
    }

    return $this->app->handle($request$type$catch);
  }

}
$dup->requestUri = null;
        $dup->baseUrl = null;
        $dup->basePath = null;
        $dup->method = null;
        $dup->format = null;

        if (!$dup->get('_format') && $this->get('_format')) {
            $dup->attributes->set('_format', $this->get('_format'));
        }

        if (!$dup->getRequestFormat(null)) {
            $dup->setRequestFormat($this->getRequestFormat(null));
        }

        return $dup;
    }

    /** * Clones the current request. * * Note that the session is not cloned as duplicated requests * are most of the time sub-requests of the main one. */
    

final class EarlyFormatSetter extends RequestFormatRouteFilter {

  /** * {@inheritdoc} */
  public function filter(RouteCollection $collection, Request $request) {
    if (is_null($request->getRequestFormat(NULL))) {
      $possible_formats = static::getAvailableFormats($collection);
      if ($possible_formats === ['api_json']) {
        $request->setRequestFormat('api_json');
      }
    }
    return $collection;
  }

}
$this->assertEquals('ISO-8859-1', $response->getCharset());
    }

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

        $response = new Response('foo');
        $request = Request::create('/');
        $request->setRequestFormat('application/json');

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

        $this->assertEquals('ISO-8859-15', $response->getCharset());
    }

    public function testSetContentLanguageHeaderWhenEmptyAndAtLeast2EnabledLocalesAreConfigured()
    {
        $listener = new ResponseListener('ISO-8859-15', true, ['fr', 'en']);
        $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...), 1);

        
$this->preloader->onFinishedRoutes(new Event());
  }

  /** * Tests onRequest on a non html request. */
  public function testOnRequestNonHtml() {
    $event = $this->getMockBuilder('\Symfony\Component\HttpKernel\Event\KernelEvent')
      ->disableOriginalConstructor()
      ->getMock();
    $request = new Request();
    $request->setRequestFormat('non-html');
    $event->expects($this->any())
      ->method('getRequest')
      ->willReturn($request);

    $this->routeProvider->expects($this->never())
      ->method('getRoutesByNames');
    $this->state->expects($this->never())
      ->method('get');

    $this->preloader->onRequest($event);
  }

  
$request = Request::create('/');
        $request->headers->set('Accept', 'application/json');
        $response->prepare($request);

        $this->assertSame('text/html; charset=UTF-8', $response->headers->get('content-type'));
    }

    public function testPrepareSetContentType()
    {
        $response = new Response('foo');
        $request = Request::create('/');
        $request->setRequestFormat('json');

        $response->prepare($request);

        $this->assertEquals('application/json', $response->headers->get('content-type'));
    }

    public function testPrepareRemovesContentForHeadRequests()
    {
        $response = new Response('foo');
        $request = Request::create('/', 'HEAD');

        

  public function testHandle() {
    $request = $this->prophesize(Request::class);

    // Default empty format list should not set any formats.     $request->setFormat()->shouldNotBeCalled();

    // Request format will be set with default format.     $request->setRequestFormat()->shouldNotBeCalled();

    // Some getContentType calls we don't really care about but have to mock.     $request_data = $this->prophesize(ParameterBag::class);
    $request_data->get('ajax_iframe_upload', FALSE)->willReturn(FALSE)->shouldBeCalled();
    $request_mock = $request->reveal();
    $request_mock->query = new ParameterBag([]);
    $request_mock->request = $request_data->reveal();

    // Calling kernel app with default arguments.     $this->app->handle($request_mock, HttpKernelInterface::MAIN_REQUEST, TRUE)
      ->shouldBeCalled()
      

class RequestFormatRouteFilterTest extends UnitTestCase {

  /** * @covers ::filter * @dataProvider filterProvider */
  public function testFilter(RouteCollection $collection$request_format, array $expected_filtered_collection) {
    $route_filter = new RequestFormatRouteFilter();

    $request = new Request();
    $request->setRequestFormat($request_format);
    $collection = $route_filter->filter($collection$request);

    $this->assertSameSize($expected_filtered_collection$collection);
    $this->assertSame($expected_filtered_collectionarray_keys($collection->all()));
  }

  public function filterProvider() {
    $route_without_format = new Route('/test');
    $route_with_format = new Route('/test');
    $route_with_format->setRequirement('_format', 'json');
    $route_with_multiple_formats = new Route('/test');
    


  /** * Sets up a request on the request stack with a specified format. * * @param string $format * The new request format. */
  protected function addRequestWithFormat($format) {
    $request = \Drupal::request();
    $request = clone $request;
    $request->setRequestFormat($format);

    \Drupal::requestStack()->push($request);
  }

  /** * Tests REST export with views render caching enabled. */
  public function testRestRenderCaching() {
    $this->drupalLogin($this->adminUser);
    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = \Drupal::service('render_cache');

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