NegotiationMiddleware.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Drupal\Core\StackMiddleware;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpKernel\HttpKernelInterface;
  5. /**
  6. * Provides a middleware to determine the content type upon the accept header.
  7. *
  8. * @todo This is a temporary solution, remove this in https://www.drupal.org/node/2364011
  9. */
  10. class NegotiationMiddleware implements HttpKernelInterface {
  11. /**
  12. * The wrapped HTTP kernel.
  13. *
  14. * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  15. */
  16. protected $app;
  17. /**
  18. * Contains a hashmap of format as key and mimetype as value.
  19. *
  20. * @var array
  21. */
  22. protected $formats = [];
  23. /**
  24. * Constructs a new NegotiationMiddleware.
  25. *
  26. * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
  27. * The wrapper HTTP kernel
  28. */
  29. public function __construct(HttpKernelInterface $app) {
  30. $this->app = $app;
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  36. // Register available mime types.
  37. foreach ($this->formats as $format => $mime_type) {
  38. $request->setFormat($format, $mime_type);
  39. }
  40. // Determine the request format using the negotiator.
  41. if ($requested_format = $this->getContentType($request)) {
  42. $request->setRequestFormat($requested_format);
  43. }
  44. return $this->app->handle($request, $type, $catch);
  45. }
  46. /**
  47. * Registers a format for a given MIME type.
  48. *
  49. * @param string $format
  50. * The format.
  51. * @param string $mime_type
  52. * The MIME type.
  53. *
  54. * @return $this
  55. */
  56. public function registerFormat($format, $mime_type) {
  57. $this->formats[$format] = $mime_type;
  58. return $this;
  59. }
  60. /**
  61. * Gets the normalized type of a request.
  62. *
  63. * The normalized type is a short, lowercase version of the format, such as
  64. * 'html', 'json' or 'atom'.
  65. *
  66. * @param \Symfony\Component\HttpFoundation\Request $request
  67. * The request object from which to extract the content type.
  68. *
  69. * @return string
  70. * The normalized type of a given request.
  71. */
  72. protected function getContentType(Request $request) {
  73. // AJAX iframe uploads need special handling, because they contain a JSON
  74. // response wrapped in <textarea>.
  75. if ($request->request->get('ajax_iframe_upload', FALSE)) {
  76. return 'iframeupload';
  77. }
  78. if ($request->query->has('_format')) {
  79. return $request->query->get('_format');
  80. }
  81. // No format was specified in the request.
  82. return NULL;
  83. }
  84. }