You are here

function restful_menu_process_callback in RESTful 7.2

Same name and namespace in other branches
  1. 7 restful.module \restful_menu_process_callback()

Page callback; Return the response for an API call.

Parameters

string $resource_name: The name of the resource (e.g. "articles").

string $version: The version, prefixed with v (e.g. v1, v2.2).

Return value

string JSON output with the result of the API call.

Throws

\Drupal\restful\Exception\ServiceUnavailableException

See also

http://tools.ietf.org/html/draft-nottingham-http-problem-06

File

./restful.module, line 232

Code

function restful_menu_process_callback($resource_name, $version = NULL) {
  $path = func_get_args();
  array_shift($path);
  if (preg_match('/^v\\d+(\\.\\d+)?$/', $version)) {
    array_shift($path);
  }
  $resource_manager = restful()
    ->getResourceManager();
  list($major_version, $minor_version) = $resource_manager
    ->getVersionFromRequest();
  $request = restful()
    ->getRequest();
  $request
    ->setViaRouter(TRUE);
  $resource = $resource_manager
    ->getPlugin($resource_name . PluginBase::DERIVATIVE_SEPARATOR . $major_version . '.' . $minor_version, $request);
  $response_headers = restful()
    ->getResponse()
    ->getHeaders();
  $version_array = $resource
    ->getVersion();
  $version_string = 'v' . $version_array['major'] . '.' . $version_array['minor'];
  $response_headers
    ->add(HttpHeader::create('X-API-Version', $version_string));

  // Vary the response with the presence of the X-API-Version or Accept headers.
  $vary = $request
    ->getHeaders()
    ->get('Vary')
    ->getValueString() ?: '';
  $additional_variations = array(
    $vary,
    'Accept',
  );
  if ($x_api_version = $request
    ->getHeaders()
    ->get('X-API-Version')
    ->getValueString()) {
    $additional_variations[] = 'X-API-Version';
  }
  if ($additional_variations) {
    $response_headers
      ->append(HttpHeader::create('Vary', implode(',', $additional_variations)));
  }

  // Always add the allow origin if configured.
  $plugin_definition = $resource
    ->getPluginDefinition();
  if (!empty($plugin_definition['allowOrigin'])) {
    $response_headers
      ->append(HttpHeader::create('Access-Control-Allow-Origin', $plugin_definition['allowOrigin']));
  }
  try {
    $resource
      ->setPath(implode('/', $path));
    $result = $resource
      ->process();
  } catch (RestfulException $e) {
    $result = _restful_build_http_api_error($e);
  } catch (Exception $e) {
    $result = array(
      'type' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1',
      'title' => $e
        ->getMessage(),
      'status' => 500,
    );
  }

  // If the user was switched during the execution thread, then switch it back.
  $resource
    ->switchUserBack();
  return $result;
}