You are here

public function FormatterManager::negotiateFormatter in RESTful 7.2

Helper function to get the default output format from the current request.

Parameters

string $accept: The Accept header.

string $formatter_name: The name of the formatter for the current resource.

Return value

FormatterInterface The formatter plugin to use.

Overrides FormatterManagerInterface::negotiateFormatter

1 call to FormatterManager::negotiateFormatter()
FormatterManager::processData in src/Formatter/FormatterManager.php
Helper function to get a formatter and apply a method.

File

src/Formatter/FormatterManager.php, line 84
Contains \Drupal\restful\Formatter\FormatterManager

Class

FormatterManager
Class FormatterManager.

Namespace

Drupal\restful\Formatter

Code

public function negotiateFormatter($accept, $formatter_name = NULL) {
  $message = 'Formatter plugin class was not found.';
  $default_formatter_name = variable_get('restful_default_output_formatter', 'json');
  try {
    if ($formatter_name) {
      return $this
        ->getPluginByName($formatter_name);
    }

    // Sometimes we will get a default Accept: */* in that case we want to
    // return the default content type and not just any.
    if (empty($accept) || $accept == '*/*') {

      // Return the default formatter.
      return $this
        ->getPluginByName($default_formatter_name);
    }
    foreach (explode(',', $accept) as $accepted_content_type) {

      // Loop through all the formatters and find the first one that matches
      // the Content-Type header.
      $accepted_content_type = trim($accepted_content_type);
      if (strpos($accepted_content_type, '*/*') === 0) {
        return $this
          ->getPluginByName($default_formatter_name);
      }
      foreach ($this->plugins as $formatter_name => $formatter) {

        /* @var FormatterInterface $formatter */
        if (static::matchContentType($formatter
          ->getContentTypeHeader(), $accepted_content_type)) {
          $formatter
            ->setConfiguration(array(
            'resource' => $this->resource,
          ));
          return $formatter;
        }
      }
    }
  } catch (PluginNotFoundException $e) {

    // Catch the exception and throw one of our own.
    $message = $e
      ->getMessage();
  }
  throw new ServiceUnavailableException($message);
}