You are here

final class EarlyFormatSetter in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Routing/EarlyFormatSetter.php \Drupal\jsonapi\Routing\EarlyFormatSetter
  2. 9 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

  • class \Drupal\jsonapi\Routing\EarlyFormatSetter extends \Drupal\Core\Routing\RequestFormatRouteFilter

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