getRequestFormat example

/** * Returns different responses depending on the request format. * * @param \Symfony\Component\HttpFoundation\Request $request * The request * * @return \Symfony\Component\HttpFoundation\Response * The response. */
  public function format(Request $request) {
    switch ($request->getRequestFormat()) {
      case 'json':
        return new JsonResponse(['some' => 'data']);

      case 'xml':
        return new Response('<xml></xml>', Response::HTTP_OK, ['Content-Type' => 'application/xml']);

      default:
        return new Response($request->getRequestFormat());
    }
  }

  

  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();

    // Make the exception available for example when rendering a block.     $request = $event->getRequest();
    $request->attributes->set('exception', $exception);

    $handled_formats = $this->getHandledFormats();

    $format = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, $request->getRequestFormat());

    if ($exception instanceof HttpExceptionInterface && (empty($handled_formats) || in_array($format$handled_formats))) {
      $method = 'on' . $exception->getStatusCode();
      // Keep just the leading number of the status code to produce either a       // 400 or a 500 method callback.       $method_fallback = 'on' . substr($exception->getStatusCode(), 0, 1) . 'xx';
      // We want to allow the method to be called and still not set a response       // if it has additional filtering logic to determine when it will apply.       // It is therefore the method's responsibility to set the response on the       // event if appropriate.       if (method_exists($this$method)) {
        

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;
  }

}
        // While the second trace is the error source and also contained in the         // message, the message doesn't contain argument values, so we output it         // once more in the backtrace.         array_shift($backtrace);

        // Generate a backtrace containing only scalar argument values.         $error['@backtrace'] = Error::formatBacktrace($backtrace);
        $message = new FormattableMarkup(Error::DEFAULT_ERROR_MESSAGE . ' <pre class="backtrace">@backtrace</pre>', $error);
      }
    }

    $content_type = $event->getRequest()->getRequestFormat() == 'html' ? 'text/html' : 'text/plain';
    $content = $this->t('The website encountered an unexpected error. Please try again later.');
    $content .= $message ? '<br><br>' . $message : '';
    $response = new Response($content, 500, ['Content-Type' => $content_type]);

    if ($exception instanceof HttpExceptionInterface) {
      $response->setStatusCode($exception->getStatusCode());
      $response->headers->add($exception->getHeaders());
    }
    else {
      $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR, '500 Service unavailable (with message)');
    }

    
$dup->pathInfo = null;
        $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. */
class PageCacheAcceptHeaderController {

  /** * Processes a request that will vary with Accept header. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return mixed */
  public function content(Request $request) {
    if ($request->getRequestFormat() === 'json' && $request->query->get('_wrapper_format') === 'drupal_ajax') {
      $response = new CacheableAjaxResponse(['content' => 'oh hai this is ajax']);
    }
    elseif ($request->getRequestFormat() === 'json') {
      $response = new CacheableJsonResponse(['content' => 'oh hai this is json']);
    }
    else {
      $response = new CacheableResponse("<p>oh hai this is html.</p>");
    }
    $response->addCacheableDependency((new CacheableMetadata())->addCacheContexts(['url.query_args:_wrapper_format']));
    return $response;
  }

}
/** * Sets a response given a (main content) render array. * * @param \Symfony\Component\HttpKernel\Event\ViewEvent $event * The event to process. */
  public function onViewRenderArray(ViewEvent $event) {
    $request = $event->getRequest();
    $result = $event->getControllerResult();

    // Render the controller result into a response if it's a render array.     if (is_array($result) && ($request->query->has(static::WRAPPER_FORMAT) || $request->getRequestFormat() == 'html')) {
      $wrapper = $request->query->get(static::WRAPPER_FORMAT, 'html');

      // Fall back to HTML if the requested wrapper envelope is not available.       $wrapper = isset($this->mainContentRenderers[$wrapper]) ? $wrapper : 'html';

      $renderer = $this->classResolver->getInstanceFromDefinition($this->mainContentRenderers[$wrapper]);
      $response = $renderer->renderResponse($result$request$this->routeMatch);
      // The main content render array is rendered into a different Response       // object, depending on the specified wrapper format.       if ($response instanceof CacheableResponseInterface) {
        $main_content_view_subscriber_cacheability = (new CacheableMetadata())->setCacheContexts(['url.query_args:' . static::WRAPPER_FORMAT]);
        

class RequestFormatRouteFilter implements FilterInterface {

  /** * {@inheritdoc} */
  public function filter(RouteCollection $collection, Request $request) {
    // Determine the request format.     $default_format = static::getDefaultFormat($collection);
    // If the request does not specify a format then use the default.     if (is_null($request->getRequestFormat(NULL))) {
      $format = $default_format;
      $request->setRequestFormat($default_format);
    }
    else {
      $format = $request->getRequestFormat($default_format);
    }

    $routes_with_requirement = [];
    $routes_without_requirement = [];
    $result_collection = new RouteCollection();
    /** @var \Symfony\Component\Routing\Route $route */
    

  public function onRespond(ViewEvent $event) {
    $request = $event->getRequest();
    $result = $event->getControllerResult();

    // If this is a render array then we assume that the router went with the     // generic controller and not one with a format. If the format requested is     // not HTML though, we can also assume that the requested format is invalid     // so we provide a 406 response.     if (is_array($result) && $request->getRequestFormat() !== 'html') {
      throw new NotAcceptableHttpException('Not acceptable format: ' . $request->getRequestFormat());
    }
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[KernelEvents::VIEW][] = ['onRespond', -10];
    return $events;
  }

}
public function testForward()
    {
        $request = Request::create('/');
        $request->setLocale('fr');
        $request->setRequestFormat('xml');

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

        $kernel = $this->createMock(HttpKernelInterface::class);
        $kernel->expects($this->once())->method('handle')->willReturnCallback(fn (Request $request) => new Response($request->getRequestFormat().'--'.$request->getLocale()));

        $container = new Container();
        $container->set('request_stack', $requestStack);
        $container->set('http_kernel', $kernel);

        $controller = $this->createController();
        $controller->setContainer($container);

        $response = $controller->forward('a_controller');
        $this->assertEquals('xml--fr', $response->getContent());
    }

    
return [
            [$event$event2],
        ];
    }

    public function testSubRequestFormat()
    {
        $listener = new ErrorListener('foo', $this->createMock(LoggerInterface::class));

        $kernel = $this->createMock(HttpKernelInterface::class);
        $kernel->expects($this->once())->method('handle')->willReturnCallback(fn (Request $request) => new Response($request->getRequestFormat()));

        $request = Request::create('/');
        $request->setRequestFormat('xml');

        $event = new ExceptionEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, new \Exception('foo'));
        $listener->onKernelException($event);

        $response = $event->getResponse();
        $this->assertEquals('xml', $response->getContent());
    }

    
// Sub-requests and programmatic calls stay in the collected profile.         if ($this->dumper || ($this->requestStack && $this->requestStack->getMainRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
            return;
        }

        // In all other conditions that remove the web debug toolbar, dumps are written on the output.         if (!$this->requestStack
            || !$response->headers->has('X-Debug-Token')
            || $response->isRedirection()
            || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html'))
            || 'html' !== $request->getRequestFormat()
            || false === strripos($response->getContent(), '</body>')
        ) {
            if ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type') ?? '', 'html')) {
                $dumper = new HtmlDumper('php://output', $this->charset);
                $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
            } else {
                $dumper = new CliDumper('php://output', $this->charset);
                if (method_exists($dumper, 'setDisplayOptions')) {
                    $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
                }
            }

            

  protected function getCacheId(Request $request) {
    // Once a cache ID is determined for the request, reuse it for the duration     // of the request. This ensures that when the cache is written, it is only     // keyed on request data that was available when it was read. For example,     // the request format might be NULL during cache lookup and then set during     // routing, in which case we want to key on NULL during writing, since that     // will be the value during lookups for subsequent requests.     if (!isset($this->cid)) {
      $cid_parts = [
        $request->getSchemeAndHttpHost() . $request->getRequestUri(),
        $request->getRequestFormat(NULL),
      ];
      $this->cid = implode(':', $cid_parts);
    }
    return $this->cid;
  }

}

class AcceptHeaderMatcher implements FilterInterface {

  /** * {@inheritdoc} */
  public function filter(RouteCollection $collection, Request $request) {
    // Generates a list of Symfony formats matching the acceptable MIME types.     // @todo replace by proper content negotiation library.     $acceptable_mime_types = $request->getAcceptableContentTypes();
    $acceptable_formats = array_filter(array_map([$request, 'getFormat']$acceptable_mime_types));
    $primary_format = $request->getRequestFormat();

    foreach ($collection as $name => $route) {
      // _format could be a |-delimited list of supported formats.       $supported_formats = array_filter(explode('|', $route->getRequirement('_format') ?? ''));

      if (empty($supported_formats)) {
        // No format restriction on the route, so it always matches. Move it to         // the end of the collection by re-adding it.         $collection->add($name$route);
      }
      elseif (in_array($primary_format$supported_formats)) {
        
$this->assertEquals(['foo' => 'foobar']$dup->query->all(), '->duplicate() overrides the query parameters if provided');
        $this->assertEquals(['foo' => 'foobar']$dup->request->all(), '->duplicate() overrides the request parameters if provided');
        $this->assertEquals(['foo' => 'foobar']$dup->attributes->all(), '->duplicate() overrides the attributes if provided');
        $this->assertEquals(['foo' => ['foobar']]$dup->headers->all(), '->duplicate() overrides the HTTP header if provided');
    }

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