function RouteEnhancer::enhance

Same name and namespace in other branches
  1. 8.9.x core/modules/jsonapi/src/Routing/RouteEnhancer.php \Drupal\jsonapi\Routing\RouteEnhancer::enhance()
  2. 10 core/modules/jsonapi/src/Routing/RouteEnhancer.php \Drupal\jsonapi\Routing\RouteEnhancer::enhance()
  3. 11.x core/modules/jsonapi/src/Routing/RouteEnhancer.php \Drupal\jsonapi\Routing\RouteEnhancer::enhance()

Overrides EnhancerInterface::enhance

File

core/modules/jsonapi/src/Routing/RouteEnhancer.php, line 23

Class

RouteEnhancer
Ensures the loaded entity matches the requested resource type.

Namespace

Drupal\jsonapi\Routing

Code

public function enhance(array $defaults, Request $request) {
    if (!Routes::isJsonApiRequest($defaults)) {
        return $defaults;
    }
    $resource_type = Routes::getResourceTypeNameFromParameters($defaults);
    $entity_type_id = $resource_type->getEntityTypeId();
    if (!isset($defaults[$entity_type_id]) || !($entity = $defaults[$entity_type_id])) {
        return $defaults;
    }
    $retrieved_bundle = $entity->bundle();
    $configured_bundle = $resource_type->getBundle();
    if ($retrieved_bundle != $configured_bundle) {
        // If the bundle in the loaded entity does not match the bundle in the
        // route (which is set based on the corresponding ResourceType), then
        // throw an exception.
        throw new NotFoundHttpException(sprintf('The loaded entity bundle (%s) does not match the configured resource (%s).', $retrieved_bundle, $configured_bundle));
    }
    return $defaults;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.