You are here

final class EarlyFormatSetter in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Routing/EarlyFormatSetter.php \Drupal\jsonapi\Routing\EarlyFormatSetter
  2. 10 core/modules/jsonapi/src/Routing/EarlyFormatSetter.php \Drupal\jsonapi\Routing\EarlyFormatSetter

Sets the 'api_json' format for requests to JSON:API resources.

Because this module places all JSON:API resources at paths prefixed with /jsonapi, and therefore not shared with other formats, \Drupal\Core\Routing\RequestFormatRouteFilter does correctly set the request format for those requests. However, it does so after other filters, such as \Drupal\Core\Routing\ContentTypeHeaderMatcher, run. If those other filters throw exceptions, we'd like the error response to be in JSON:API format as well, so we set that format here, in a higher priority (earlier running) filter. This works so long as the resource format can be determined before running any other filters, which is the case for JSON:API resources per above.

@internal

Hierarchy

Expanded class hierarchy of EarlyFormatSetter

1 string reference to 'EarlyFormatSetter'
jsonapi.services.yml in core/modules/jsonapi/jsonapi.services.yml
core/modules/jsonapi/jsonapi.services.yml
1 service uses EarlyFormatSetter
jsonapi.route_filter.format_setter in core/modules/jsonapi/jsonapi.services.yml
Drupal\jsonapi\Routing\EarlyFormatSetter

File

core/modules/jsonapi/src/Routing/EarlyFormatSetter.php, line 25

Namespace

Drupal\jsonapi\Routing
View source
final class EarlyFormatSetter extends RequestFormatRouteFilter {

  /**
   * {@inheritdoc}
   */
  public function filter(RouteCollection $collection, Request $request) {
    if (is_null($request
      ->getRequestFormat(NULL))) {
      $possible_formats = static::getAvailableFormats($collection);
      if ($possible_formats === [
        'api_json',
      ]) {
        $request
          ->setRequestFormat('api_json');
      }
    }
    return $collection;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
EarlyFormatSetter::filter public function Filters the route collection against a request and returns all matching routes. Overrides RequestFormatRouteFilter::filter
RequestFormatRouteFilter::getAvailableFormats protected static function Gets the set of formats across all routes in the collection.
RequestFormatRouteFilter::getDefaultFormat protected static function Determines the default request format.