AcceptHeaderMiddleware.php in Drupal 10
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;
class AcceptHeaderMiddleware implements HttpKernelInterface {
public function __construct(HttpKernelInterface $app) {
$this->app = $app;
}
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);
}
}