You are here

protected function EntityResource::getJsonApiParams in JSON:API Extras 8.3

Extracts JSON:API query parameters from the request.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The request object.

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The JSON:API resource type.

Return value

array An array of JSON:API parameters like `sort` and `filter`.

Overrides EntityResource::getJsonApiParams

File

modules/jsonapi_defaults/src/Controller/EntityResource.php, line 22

Class

EntityResource
Overrides jsonapi module EntityResource controller.

Namespace

Drupal\jsonapi_defaults\Controller

Code

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

  // If this is a related resource, then we need to swap to the new resource
  // type.
  $related_field = $request->attributes
    ->get('_on_relationship') ? NULL : $request->attributes
    ->get('related');
  try {
    $resource_type = static::correctResourceTypeOnRelated($related_field, $resource_type);
  } catch (\LengthException $e) {
    watchdog_exception('jsonapi_defaults', $e);
    $resource_type = NULL;
  }
  if (!$resource_type instanceof ConfigurableResourceType) {
    return parent::getJsonApiParams($request, $resource_type);
  }
  $resource_config = $resource_type
    ->getJsonapiResourceConfig();
  if (!$resource_config instanceof JsonapiResourceConfig) {
    return parent::getJsonApiParams($request, $resource_type);
  }
  $default_filter_input = $resource_config
    ->getThirdPartySetting('jsonapi_defaults', 'default_filter', []);
  $default_sorting_input = $resource_config
    ->getThirdPartySetting('jsonapi_defaults', 'default_sorting', []);
  $default_filter = [];
  $default_sorting = [];
  foreach ($default_filter_input as $key => $value) {
    if (substr($key, 0, 6) === 'filter') {
      $key = str_replace('filter:', '', $key);

      // @todo Replace this with use of the NestedArray utility.
      $this
        ->setFilterValue($default_filter, $key, $value);
    }
  }
  foreach ($default_sorting_input as $key => $value) {
    if (substr($key, 0, 4) === 'sort') {
      $key = str_replace('sort:', '', $key);

      // @todo Replace this with use of the NestedArray utility.
      $this
        ->setFilterValue($default_sorting, $key, $value);
    }
  }
  $filters = array_merge($default_filter, $request->query
    ->get('filter', []));
  $sorting = array_merge($default_sorting, $request->query
    ->get('sort', []));
  if (!empty($filters)) {
    $request->query
      ->set('filter', $filters);
  }
  if (!empty($sorting)) {
    $request->query
      ->set('sort', $sorting);
  }

  // Implements overridden page limits.
  $params = parent::getJsonApiParams($request, $resource_type);
  $this
    ->setPageLimit($request, $resource_config, $params);
  return $params;
}