Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / lib / Drupal / Core / StackMiddleware / NegotiationMiddleware.php
1 <?php
2
3 namespace Drupal\Core\StackMiddleware;
4
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\HttpKernel\HttpKernelInterface;
7
8 /**
9  * Provides a middleware to determine the content type upon the accept header.
10  *
11  * @todo This is a temporary solution, remove this in https://www.drupal.org/node/2364011
12  */
13 class NegotiationMiddleware implements HttpKernelInterface {
14
15   /**
16    * The wrapped HTTP kernel.
17    *
18    * @var \Symfony\Component\HttpKernel\HttpKernelInterface
19    */
20   protected $app;
21
22   /**
23    * Contains a hashmap of format as key and mimetype as value.
24    *
25    * @var array
26    */
27   protected $formats = [];
28
29   /**
30    * Constructs a new NegotiationMiddleware.
31    *
32    * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
33    *   The wrapper HTTP kernel
34    */
35   public function __construct(HttpKernelInterface $app) {
36     $this->app = $app;
37   }
38
39   /**
40    * {@inheritdoc}
41    */
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);
46     }
47
48     // Determine the request format using the negotiator.
49     $request->setRequestFormat($this->getContentType($request));
50     return $this->app->handle($request, $type, $catch);
51   }
52
53   /**
54    * Registers a format for a given MIME type.
55    *
56    * @param string $format
57    *   The format.
58    * @param string $mime_type
59    *   The MIME type.
60    *
61    * @return $this
62    */
63   public function registerFormat($format, $mime_type) {
64     $this->formats[$format] = $mime_type;
65     return $this;
66   }
67
68   /**
69    * Gets the normalized type of a request.
70    *
71    * The normalized type is a short, lowercase version of the format, such as
72    * 'html', 'json' or 'atom'.
73    *
74    * @param \Symfony\Component\HttpFoundation\Request $request
75    *   The request object from which to extract the content type.
76    *
77    * @return string
78    *   The normalized type of a given request.
79    */
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';
85     }
86
87     if ($request->query->has('_format')) {
88       return $request->query->get('_format');
89     }
90
91     // Do HTML last so that it always wins.
92     return 'html';
93   }
94
95 }