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 $request->setRequestFormat($this->getContentType($request));
50 return $this->app->handle($request, $type, $catch);
54 * Registers a format for a given MIME type.
56 * @param string $format
58 * @param string $mime_type
63 public function registerFormat($format, $mime_type) {
64 $this->formats[$format] = $mime_type;
69 * Gets the normalized type of a request.
71 * The normalized type is a short, lowercase version of the format, such as
72 * 'html', 'json' or 'atom'.
74 * @param \Symfony\Component\HttpFoundation\Request $request
75 * The request object from which to extract the content type.
78 * The normalized type of a given request.
80 protected function getContentType(Request $request) {
81 // AJAX iframe uploads need special handling, because they contain a JSON
82 // response wrapped in <textarea>.
83 if ($request->request->get('ajax_iframe_upload', FALSE)) {
84 return 'iframeupload';
87 if ($request->query->has('_format')) {
88 return $request->query->get('_format');
91 // Do HTML last so that it always wins.