class AcceptHeaderMiddleware
Example implementation of "accept header"-based content negotiation.
Hierarchy
- class \Drupal\accept_header_routing_test\AcceptHeaderMiddleware implements \Symfony\Component\HttpKernel\HttpKernelInterface
 
Expanded class hierarchy of AcceptHeaderMiddleware
File
- 
              core/
modules/ system/ tests/ modules/ accept_header_routing_test/ src/ AcceptHeaderMiddleware.php, line 14  
Namespace
Drupal\accept_header_routing_testView source
class AcceptHeaderMiddleware implements HttpKernelInterface {
  
  /**
   * The app kernel.
   */
  protected HttpKernelInterface $httpKernel;
  
  /**
   * Constructs a new AcceptHeaderMiddleware instance.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   The app.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }
  
  /**
   * {@inheritdoc}
   */
  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->httpKernel
      ->handle($request, $type, $catch);
  }
}
Members
| Title Sort descending | Modifiers | Object type | Summary | 
|---|---|---|---|
| AcceptHeaderMiddleware::$httpKernel | protected | property | The app kernel. | 
| AcceptHeaderMiddleware::handle | public | function | |
| AcceptHeaderMiddleware::__construct | public | function | Constructs a new AcceptHeaderMiddleware instance. | 
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.