You are here

function restful_delivery in RESTful 7

Same name and namespace in other branches
  1. 7.2 restful.module \restful_delivery()

Returns data in JSON format.

We do not use drupal_json_output(), in order to maintain the "Content-Type" header.

Parameters

$var: (optional) If set, the variable will be converted to JSON and output.

string $method: Name of the method for the formatter.

See also

restful_menu_process_callback()

3 calls to restful_delivery()
restful_deliver_menu_not_found in ./restful.module
Delivers a not found (404) error.
restful_formatted_delivery in ./restful.module
Returns data in JSON format using data preparation in the formatter plugin.
restful_unprepared_delivery in ./restful.module
Returns data in JSON format not using data preparation in the formatter plugin.

File

./restful.module, line 621

Code

function restful_delivery($var = NULL, $method = 'format') {
  if ($restful_handler = restful_get_restful_handler_for_path()) {

    // Allow the handler to change the HTTP headers.
    foreach ($restful_handler
      ->getHttpHeaders() as $key => $value) {
      drupal_add_http_header($key, $value);
    }
  }
  if (!isset($var)) {
    return;
  }
  if (is_int($var)) {
    _restful_get_json_from_menu_status($var);

    // Adhere to the API Problem draft proposal.
    drupal_add_http_header('Status', $var['status']);
    drupal_add_http_header('Content-Type', 'application/problem+json; charset=utf-8');
  }

  // If we are returning from an OPTIONS call, always use render.
  if ($restful_handler && $restful_handler
    ->getMethod() == \RestfulInterface::OPTIONS) {
    $method = 'render';
  }

  // Get the formatter for the current resource.
  try {
    $formatter_handler = \RestfulManager::outputFormat($restful_handler);
    $output = $formatter_handler
      ->{$method}($var);

    // The content type header is modified after the massaging if there is
    // an error code. Therefore we need to set the content type header after
    // formatting the output.
    drupal_add_http_header('Content-Type', $formatter_handler
      ->getContentTypeHeader());
  } catch (\RestfulException $e) {

    // Handle if the formatter does not exist.
    drupal_add_http_header('Status', $e
      ->getCode());
    echo $e
      ->getMessage();
    return;
  }
  print $output;
  \RestfulManager::pageFooter();
}