AcceptHeaderMiddleware.php

Same filename in other branches
  1. 8.9.x core/modules/system/tests/modules/accept_header_routing_test/src/AcceptHeaderMiddleware.php
  2. 10 core/modules/system/tests/modules/accept_header_routing_test/src/AcceptHeaderMiddleware.php
  3. 11.x core/modules/system/tests/modules/accept_header_routing_test/src/AcceptHeaderMiddleware.php

Namespace

Drupal\accept_header_routing_test

File

core/modules/system/tests/modules/accept_header_routing_test/src/AcceptHeaderMiddleware.php

View source
<?php

namespace Drupal\accept_header_routing_test;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Example implementation of "accept header"-based content negotiation.
 */
class AcceptHeaderMiddleware implements HttpKernelInterface {
    
    /**
     * The app kernel.
     */
    protected $app;
    
    /**
     * Constructs a new AcceptHeaderMiddleware instance.
     *
     * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
     *   The app.
     */
    public function __construct(HttpKernelInterface $app) {
        $this->app = $app;
    }
    
    /**
     * {@inheritdoc}
     */
    public function handle(Request $request, $type = self::MASTER_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);
    }

}

Classes

Title Deprecated Summary
AcceptHeaderMiddleware Example implementation of "accept header"-based content negotiation.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.