You are here

protected function RequestHandler::deserialize in JSON:API 8

Deserializes request body, if any.

Parameters

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

\Drupal\jsonapi\ResourceType\ResourceType $resource_type: The JSON API resource type for the current request.

Return value

array|null An object normalization, if there is a valid request body. NULL if there is no request body.

Throws

\Symfony\Component\HttpKernel\Exception\BadRequestHttpException Thrown if the request body cannot be decoded, or when no request body was provided with a POST or PATCH request.

\Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException Thrown if the request body cannot be denormalized.

1 call to RequestHandler::deserialize()
RequestHandler::handle in src/Controller/RequestHandler.php
Handles a JSON API request.

File

src/Controller/RequestHandler.php, line 158

Class

RequestHandler
Acts as request forwarder for \Drupal\jsonapi\Controller\EntityResource.

Namespace

Drupal\jsonapi\Controller

Code

protected function deserialize(Request $request, ResourceType $resource_type) {
  if ($request
    ->isMethodSafe(FALSE)) {
    return NULL;
  }

  // Deserialize incoming data if available.
  $received = $request
    ->getContent();
  $unserialized = NULL;
  if (!empty($received)) {

    // First decode the request data. We can then determine if the
    // serialized data was malformed.
    try {
      $unserialized = $this->serializer
        ->decode($received, 'api_json');
    } catch (UnexpectedValueException $e) {

      // If an exception was thrown at this stage, there was a problem
      // decoding the data. Throw a 400 http exception.
      throw new BadRequestHttpException($e
        ->getMessage());
    }
    $field_related = $resource_type
      ->getInternalName($request
      ->get('related'));
    try {
      $unserialized = $this->serializer
        ->denormalize($unserialized, $request
        ->get('serialization_class'), 'api_json', [
        'related' => $field_related,
        'target_entity' => $request
          ->get($resource_type
          ->getEntityTypeId()),
        'resource_type' => $resource_type,
      ]);
    } catch (UnexpectedValueException $e) {
      throw new UnprocessableEntityHttpException($e
        ->getMessage());
    } catch (InvalidArgumentException $e) {
      throw new UnprocessableEntityHttpException($e
        ->getMessage());
    }
  }
  elseif ($request
    ->isMethod('POST') || $request
    ->isMethod('PATCH')) {
    throw new BadRequestHttpException('Empty request body.');
  }
  return $unserialized;
}