You are here

protected function RequestHandler::deserialize in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/rest/src/RequestHandler.php \Drupal\rest\RequestHandler::deserialize()

Deserializes request body, if any.

Parameters

\Drupal\Core\Routing\RouteMatchInterface $route_match: The route match.

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

\Drupal\rest\Plugin\ResourceInterface $resource: The REST resource plugin.

Return value

array|null An object normalization, ikf 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.

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

1 call to RequestHandler::deserialize()
RequestHandler::handle in core/modules/rest/src/RequestHandler.php
Handles a REST API request.

File

core/modules/rest/src/RequestHandler.php, line 155

Class

RequestHandler
Acts as intermediate request forwarder for resource plugins.

Namespace

Drupal\rest

Code

protected function deserialize(RouteMatchInterface $route_match, Request $request, ResourceInterface $resource) {

  // Deserialize incoming data if available.
  $received = $request
    ->getContent();
  $unserialized = NULL;
  if (!empty($received)) {
    $method = static::getNormalizedRequestMethod($route_match);
    $format = $request
      ->getContentType();
    $definition = $resource
      ->getPluginDefinition();

    // First decode the request data. We can then determine if the
    // serialized data was malformed.
    try {
      $unserialized = $this->serializer
        ->decode($received, $format, [
        'request_method' => $method,
      ]);
    } 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());
    }

    // Then attempt to denormalize if there is a serialization class.
    if (!empty($definition['serialization_class'])) {
      try {
        $unserialized = $this->serializer
          ->denormalize($unserialized, $definition['serialization_class'], $format, [
          'request_method' => $method,
        ]);
      } catch (UnexpectedValueException $e) {
        throw new UnprocessableEntityHttpException($e
          ->getMessage());
      } catch (InvalidArgumentException $e) {
        throw new UnprocessableEntityHttpException($e
          ->getMessage());
      }
    }
  }
  return $unserialized;
}