NegotiationMiddleware.php 2.04 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<?php

/**
 * @file
 * Contains \Drupal\Core\StackMiddleware\NegotationMiddleware.
 */

namespace Drupal\Core\StackMiddleware;

use Drupal\Core\ContentNegotiation;
use Drupal\Core\ContentNegotiationInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Provides a middleware to determine the content type upon the accept header.
 *
 * @todo This is a temporary solution, remove this in https://www.drupal.org/node/2364011
 */
class NegotiationMiddleware implements HttpKernelInterface {

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $app;

  /**
   * The content negotiator.
   *
   * @var \Drupal\Core\ContentNegotiation
   */
  protected $negotiator;

  /**
   * Contains a hashmap of format as key and mimetype as value.
   *
   * @var array
   */
41
  protected $formats = [];
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

  /**
   * Constructs a new NegotiationMiddleware.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
   *   The wrapper HTTP kernel
   * @param \Drupal\Core\ContentNegotiation $negotiator
   *   The content negotiator.
   */
  public function __construct(HttpKernelInterface $app, ContentNegotiation $negotiator) {
    $this->app = $app;
    $this->negotiator = $negotiator;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) {
60
    // Register available mime types.
61 62 63 64
    foreach ($this->formats as $format => $mime_type) {
      $request->setFormat($format, $mime_type);
    }

65
    // Determine the request format using the negotiator.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    $request->setRequestFormat($this->negotiator->getContentType($request));
    return $this->app->handle($request, $type, $catch);
  }

  /**
   * Registers a format for a given MIME type.
   *
   * @param string $format
   *   The format.
   * @param string $mime_type
   *   The MIME type.
   *
   * @return $this
   */
  public function registerFormat($format, $mime_type) {
    $this->formats[$format] = $mime_type;
    return $this;
  }

}