3 namespace Drupal\Core\StackMiddleware;
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\HttpKernel\HttpKernelInterface;
9 * Provides a middleware to determine the content type upon the accept header.
11 * @todo This is a temporary solution, remove this in https://www.drupal.org/node/2364011
13 class NegotiationMiddleware implements HttpKernelInterface {
16 * The wrapped HTTP kernel.
18 * @var \Symfony\Component\HttpKernel\HttpKernelInterface
23 * Contains a hashmap of format as key and mimetype as value.
27 protected $formats = [];
30 * Constructs a new NegotiationMiddleware.
32 * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
33 * The wrapper HTTP kernel
35 public function __construct(HttpKernelInterface $app) {
42 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
43 // Register available mime types.
44 foreach ($this->formats as $format => $mime_type) {
45 $request->setFormat($format, $mime_type);
48 // Determine the request format using the negotiator.
49 if ($requested_format = $this->getContentType($request)) {
50 $request->setRequestFormat($requested_format);
52 return $this->app->handle($request, $type, $catch);
56 * Registers a format for a given MIME type.
58 * @param string $format
60 * @param string $mime_type
65 public function registerFormat($format, $mime_type) {
66 $this->formats[$format] = $mime_type;
71 * Gets the normalized type of a request.
73 * The normalized type is a short, lowercase version of the format, such as
74 * 'html', 'json' or 'atom'.
76 * @param \Symfony\Component\HttpFoundation\Request $request
77 * The request object from which to extract the content type.
80 * The normalized type of a given request.
82 protected function getContentType(Request $request) {
83 // AJAX iframe uploads need special handling, because they contain a JSON
84 // response wrapped in <textarea>.
85 if ($request->request->get('ajax_iframe_upload', FALSE)) {
86 return 'iframeupload';
89 if ($request->query->has('_format')) {
90 return $request->query->get('_format');
93 // No format was specified in the request.