You are here

public function ServicesContentTypeNegotiator::getResponseFormatContentTypeNegotiations in Services 7.3

Determine response format and mime type using headers to negotiate content types.

Parameters

string $mime_type: Mime type. This variable to be overriden.

string $canonical_path: Canonical path of the request.

array $formats: Enabled formats by endpoint.

Return value

string Negotiated response format. For example 'json'.

Overrides ServicesContentTypeNegotiatorInterface::getResponseFormatContentTypeNegotiations

File

servers/rest_server/includes/ServicesContentTypeNegotiator.inc, line 71

Class

ServicesContentTypeNegotiator
Class used to do Content Type negotiation.

Code

public function getResponseFormatContentTypeNegotiations(&$mime_type, $canonical_path, $formats, $context) {
  drupal_add_http_header('Vary', 'Accept');

  // Negotiate response format based on accept-headers if we
  // don't have a response format.
  $mime_candidates = array();
  $mime_map = array();
  foreach ($formats as $format => $formatter) {
    foreach ($formatter['mime types'] as $m) {
      $mime_candidates[] = $m;
      $mime_map[$m] = $format;
    }
  }

  // Get the best matching format, default to json
  $response_format = variable_get('rest_server_default_response_format', 'json');
  $http_accept = $context
    ->getServerVariable('HTTP_ACCEPT');
  if (!empty($http_accept)) {
    $mime = $this
      ->mimeParse();
    $mime_type = $mime
      ->best_match($mime_candidates, $http_accept);
    $response_format = isset($mime_map[$mime_type]) ? $mime_map[$mime_type] : '';
  }
  return $response_format;
}