You are here

protected function JsonApiDocumentTopLevelNormalizer::expandContext in JSON:API 8

Expand the context information based on the current request context.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request to get the URL params from to expand the context.

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The resource type to translate to internal fields.

Return value

array The expanded context.

1 call to JsonApiDocumentTopLevelNormalizer::expandContext()
JsonApiDocumentTopLevelNormalizer::normalize in src/Normalizer/JsonApiDocumentTopLevelNormalizer.php
Normalizes an object into a set of arrays/scalars.

File

src/Normalizer/JsonApiDocumentTopLevelNormalizer.php, line 219

Class

JsonApiDocumentTopLevelNormalizer
Normalizes the top-level document according to the JSON API specification.

Namespace

Drupal\jsonapi\Normalizer

Code

protected function expandContext(Request $request, ResourceType $resource_type) {

  // Translate ALL the includes from the public field names to the internal.
  $includes = array_filter(explode(',', $request->query
    ->get('include')));

  // The primary resource type for 'related' routes is different than the
  // primary resource type of individual and relationship routes and is
  // determined by the relationship field name.
  $related = $request
    ->get('_on_relationship') ? FALSE : $request
    ->get('related');
  $public_includes = array_map(function ($include) use ($resource_type, $related) {
    $trimmed = trim($include);

    // If the request is a related route, prefix the path with the related
    // field name so that the path can be resolved from the base resource
    // type. Then, remove it after the path is resolved.
    $path_parts = explode('.', $related ? "{$related}.{$trimmed}" : $trimmed);
    return array_map(function ($resolved) use ($related) {
      return implode('.', $related ? array_slice($resolved, 1) : $resolved);
    }, FieldResolver::resolveInternalIncludePath($resource_type, $path_parts));
  }, $includes);

  // Flatten the resolved possible include paths.
  $public_includes = array_reduce($public_includes, 'array_merge', []);

  // Build the expanded context.
  $context = [
    'account' => NULL,
    'sparse_fieldset' => NULL,
    'resource_type' => NULL,
    'include' => $public_includes,
    'expanded' => TRUE,
  ];
  if ($request->query
    ->get('fields')) {
    $context['sparse_fieldset'] = array_map(function ($item) {
      return explode(',', $item);
    }, $request->query
      ->get('fields'));
  }
  return $context;
}